我正在两个表之间执行MERGE
MERGE indexdecomp.Constituent targ
USING (SELECT ic.ConstituentName
FROM indexdecomp.IndexConstituents ic) src
ON (((targ.Name = src.ConstituentName) OR (targ.Name IS NULL AND src.ConstituentName IS NULL)))
WHEN NOT MATCHED BY TARGET THEN
UPDATE SET
targ.Name = src.ConstituentName
;
在我的 ON
子句中,我有以下谓词:
(targ.Name = src.ConstituentName) OR (targ.Name IS NULL AND src.ConstituentName IS NULL)
我有这个谓词,因为如果两个名称相等或两个名称都为“空”,我认为它是匹配的。
是否有更好或更传统的方法来处理两个 null
列之间的相等性?哪种方式执行速度最快?
最佳答案
您可以这样做:( SQL ref )
SET ANSI_NULLS OFF;
MERGE indexdecomp.Constituent targ
USING (SELECT ic.ConstituentName
FROM #IndexConstituents ic) src
ON (((targ.Name = src.ConstituentName)))
WHEN NOT MATCHED BY TARGET THEN
UPDATE SET
targ.Name = src.ConstituentName;
SET ANSI_NULLS ON;
但是,将谓词混为一谈似乎是一个相当繁重的权衡,而且两者都不是很可读。实际上,您可以使用接受两个字符串参数并返回 bool 值的 UDF 来抽象这种困惑。
类似于:
create function StrNullCompare(@a varchar(max), @b varchar(max))
returns int
as
begin
if ((@a = @b) or (@a is null and @b is null)) return 1;
return 0;
end
-- tests
select dbo.StrNullCompare('wer', 'were');
select dbo.StrNullCompare('wer', 'wer');
select dbo.StrNullCompare('hi', null);
select dbo.StrNullCompare(null, null);
你的谓词变成:
(dbo.StrNullCompare(targ.Name, src.ConstituentName)=1)
关于sql - 在 SQL 中等同 NULL 列的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13750842/