SQL 中没有任何值会相等(或“不相等”)NULL
。理解以下真值表:
NULL = NULL yields NULL -- not FALSE!
NULL != NULL yields NULL -- not TRUE!
[ANY] = NULL yields NULL -- not FALSE!
[ANY] != NULL yields NULL -- not TRUE!
由于以下是等价的...
[expression] IN (a, b, c)
[expression] = ANY (a, b, c)
[expression] = a OR [expression] = b OR [expression] = c
...您不能NULL
放在IN predicate
. NULL
有趣的是,当您将a 放在右侧时,情况会变得更糟NOT IN predicate
:
[expression] NOT IN (a, b, c)
[expression] != ANY (a, b, c)
[expression] != a AND [expression] != b AND [expression] != c
如果b
是NULL
,则整个表达式将变为NULL
(或可能FALSE
),但绝不会变为TRUE
。NOT IN (subselect)
谓词也是如此!所以,永远不要这样做:
[expression] NOT IN (NULL, 1, 2)
在您的情况下,正确的解决方案使用 aNULL predicate
代替。做这个:
UPDATE Details
SET HowHear_ID = CASE
WHEN HowHear_ID = '' THEN 25
WHEN HowHear_ID IS NULL THEN 25 -- Use a NULL predicate here
WHEN HowHear_ID = 7 THEN 25
WHEN HowHear_ID = 8 THEN 5
WHEN HowHear_ID = 16 THEN 25
WHEN HowHear_ID = 17 THEN 16
END
WHERE HowHear_ID IN ('',7,8,16,17)
OR HowHear_ID IS NULL -- Use a NULL predicate here
或这个:
WHERE COALESCE(HowHear_ID, '') IN ('',7,8,16,17)