在TSQL中,以下示例会产生不同的结果吗?

问题描述 投票:0回答:2

我必须在TSQL中更改更新查询以包含以下代码:

(uh.FirstName != cu.FirstName or isnull(uh.FirstName,'|||') != isnull(cu.Firstname,'|||')

但在我看来,这似乎是多余的,最好只使用第二部分:

isnull(uh.FirstName,'|||') != isnull(cu.Firstname,'|||')

我错过了什么吗?

tsql optimization isnull
2个回答
1
投票

它看起来像ISNULL(x,'|||')只是试图处理考虑等价的空值。您必须处理每个空案例并可能加倍null,具体取决于是否为“匹配”。这是我的建议,注释行是选项,具体取决于你想如何处理double null。

(
    uh.FirstName != cu.FirstName 
        OR uh.FirstName IS NULL AND cu.FirstName IS NOT NULL
        OR uh.FirstName IS NOT NULL AND cur.FirstName IS NULL
        --OR uh.FirstName IS NULL AND cur.FirstName IS NULL
)

。不确定合并是否比替换和比较更快,但我的猜测是它会。它也不允许比较'|||'的模糊性为NULL将导致该解决方案产生错误结果。

*在HABO评论后修正


0
投票

除非您希望任何列实际包含三个管道('|||')的文字字符串值,否则您可以安全地使用第二个代码段。

快速演示:

DECLARE @T AS TABLE
(
    c1 varchar(5),
    c2 varchar(5)
);

INSERT INTO @T VALUES
('a', 'a'), 
('a', 'b'), 
('a', null), 
(null, 'a'), 
(null, null), 
('b', 'a');


SELECT *, 'First' as example
FROM @T
WHERE c1 != c2 OR ISNULL(c1, '|||') != ISNULL(c2, '|||')

SELECT *, 'Second' as example
FROM @T
WHERE ISNULL(c1, '|||') != ISNULL(c2, '|||')

结果:

c1      c2      example
a       b       First
a       NULL    First
NULL    a       First
b       a       First

c1      c2      example
a       b       Second
a       NULL    Second
NULL    a       Second
b       a       Second
© www.soinside.com 2019 - 2024. All rights reserved.