我有一个SQL脚本,该脚本具有查询多个表以搜索值的功能,但是它只能检查下一个表(如果第一个表返回空值)。 我正在使用case语句,检查IS NULL THEN等-参见下文。 必须有一个更简单的方法来做到这一点?
CASE
WHEN
CASE
WHEN
CASE
WHEN
SELECT accountcode from a238 where reference='xyz'
IS NULL THEN
SELECT accountcode from a241 where reference='xyz'
ELSE
SELECT accountcode from a238 where reference='xyz'
END
IS NULL THEN
SELECT accountcode from a240 where reference='xyz'
ELSE
CASE
WHEN
SELECT accountcode from a238 where reference='xyz'
IS NULL THEN
SELECT accountcode from a241 where reference='xyz'
ELSE
SELECT accountcode from a238 where reference='xyz'
END
END
IS NULL THEN
SELECT accountcode from a239 where reference='xyz'
ELSE
CASE
WHEN
CASE
WHEN
SELECT accountcode from a238 where reference='xyz'
IS NULL THEN
SELECT accountcode from a241 where reference='xyz'
ELSE
SELECT accountcode from a238 where reference='xyz'
END
IS NULL THEN
SELECT accountcode from a240 where reference='xyz'
ELSE
CASE
WHEN
SELECT accountcode from a238 where reference='xyz'
IS NULL THEN
SELECT accountcode from a241 where reference='xyz'
ELSE
SELECT accountcode from a238 where reference='xyz'
END
END
END
此代码有效,但使用和阅读时有点麻烦。 有人也可以指导我吗?
欢呼
答案 0 :(得分:3)
如果您需要调试或修改某些内容,那么该查询将非常麻烦。在评论中感谢Parfait对完全外部连接的建议。另外,您可以使用COALESCE()
替换所有CASE
语句。
使用嵌套和类似的表名,我有可能错过了一些东西,但这就是这个主意。
declare @referenceCode varchar(3) = 'xyz'
select
COALESCE(a238.accountcode, a241.accountcode, a240.accountcode, a239.accountcode) as account_code
from a238
full outer join a241 on a241.reference = @referenceCode
full outer join a240 on a240.reference = @referenceCode
full outer join a239 on a239.reference = @referenceCode
where a238.reference = @referenceCode