我需要从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 :(得分:1)
唯一可能产生"生产" null值是表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'