2017-08-25 24 views
0

我需要从SQL Server 2008转换此查询相同的结果:我不能让这些查询

select distinct 
    i.art, i.des1, isnull(l.porc_tol, 0) as porc_tol, 
    0.0, a.cia, a.alm, 
    i.art, i.lin, i.s_lin, i.fam, i.s_fam, i.marca, a.cve_pro 
from 
    invsas v (nolock), 
    invars s (nolock), 
    inviar i (nolock), 
    invart a (nolock), 
    invtol l (nolock) 
where 
    v.cia = 'DEM' 
    and v.cve_suc = '001' 
    and s.cia = v.cia 
    and s.alm = v.alm 
    and s.sub_alm = v.cve 
    and i.art = s.cve_art 
    and a.cia = s.cia 
    and a.alm = s.alm 
    and a.art = i.art 
    and l.cia =* s.cia 
    and l.suc =* v.cve_suc 
    and l.cve_art =* i.art 

到SQL Server 2012的我做了这些变化:

SELECT DISTINCT 
    i.art, i.des1, ISNULL(l.porc_tol, 0) as porc_tol, 
    0.0, a.cia, a.alm, 
    i.art, i.lin, i.s_lin, i.fam, i.s_fam, i.marca, a.cve_pro 
FROM 
    invart a (nolock), 
    invtol l (nolock) 
RIGHT OUTER JOIN 
    invars s ON l.cia = s.cia 
RIGHT OUTER JOIN 
    invsas v on l.suc = v.cve_suc 
RIGHT OUTER JOIN 
    inviar i on l.cve_art = i.art 
WHERE 
    v.cia = 'DEM' 
    AND v.cve_suc = '001' 
    AND s.cia = v.cia 
    AND s.alm = v.alm 
    AND s.sub_alm = v.cve 
    AND i.art = s.cve_art 
    AND a.cia = s.cia 
    AND a.alm = s.alm 
    AND a.art = i.art 

但是,当我运行这两个查询时,我得到不同的结果。什么可能是错误的?

+0

我的错误 选择不同的我。 art,i.des1,isnull(l.porc_tol,0)作为porc_tol,0.0,a.cia,a.alm,i.art,i.lin, – Fernando

回答

1

唯一可能“产生”空值的表是l,它参与了与其他几个表的外连接。在您的版本中,您还可以使用from子句中的逗号分隔符,并在where子句中加入条件。这真是两种世界的混合语法。这对于确定外连接的范围而言可能会造成混淆。

我建议这个“翻译”,其中除了最后一个表是所有内部加盟,以然后使用一个外连接包括在查询中的最后一个表:

select distinct 
      i.art, i.des1, isnull(l.porc_tol,0) as porc_tol, 0.0, a.cia, 
      a.alm, i.art, i.lin, i.s_lin, i.fam, i.s_fam, i.marca, a.cve_pro 
from  invsas v (nolock) 
inner join invars s (nolock) 
     on s.cia = v.cia 
     and s.alm = v.alm 
     and s.sub_alm = v.cve 
inner join inviar i (nolock) 
     on i.art = s.cve_art 
inner join invart a (nolock) 
     on a.cia = s.cia 
     and a.alm = s.alm 
     and a.art = i.art 
left join invtol l (nolock) 
     on l.cia = s.cia 
     and l.suc = v.cve_suc 
     and l.cve_art = i.art 
where  v.cia = 'DEM' 
     and v.cve_suc ='001'