如何编写一个 WHERE 以等于两列同时包含 NULL 值和空值
How to write a WHERE to equate on two columns contains both NULL and empty values
鉴于我的 table 结构,现在我需要编写一个查询来比较 "STRVAL1 and STRVAL2" 和 "BVAL1 and BVAL2",如果两者不相同,则应返回该行。
预期结果...
请使用下面的脚本获取数据
DECLARE @TAB TABLE (ID INT, STRVAL1 VARCHAR(8), STRVAL2 VARCHAR(8), BVAL1 BIT, BVAL2 BIT)
INSERT INTO @TAB VALUES
(1, NULL, NULL, NULL, NULL)
, (2, '', NULL, NULL, NULL)
, (3, '', '', NULL, NULL)
, (4, 'VAL', 'VAL', NULL, NULL)
, (5, 'VAL1', 'VAL2', NULL, NULL)
, (6, NULL, NULL, 0, NULL)
, (7, NULL, NULL, 0, 0)
, (8, NULL, NULL, 1, 1)
, (9, NULL, NULL, 1, 0)
SELECT ID, STRVAL1, STRVAL2, BVAL1, BVAL2
FROM @TAB
您可以只使用比较,尽管 NULL
使这有点麻烦:
select t.*
from @tab t
where ((strval1 <> strval2) or
(strval1 is null and strval2 is not null) or
(strval1 is not null and strval2 is null)
) or
((bval1 <> bval2) or
(bval1 is null and bval2 is not null) or
(bval1 is not null and bval2 is null)
);
您需要组合测试。
select ... from ... where
(strval1 is null and strval2 is not null) or
(strval1 is not null and strval2 is null) or
(strval1 != strval2) or
(bval1 is null and bval2 is not null) or
(bval1 is not null and bval2 is null) or
(bval1 != bval2)
鉴于我的 table 结构,现在我需要编写一个查询来比较 "STRVAL1 and STRVAL2" 和 "BVAL1 and BVAL2",如果两者不相同,则应返回该行。
预期结果...
请使用下面的脚本获取数据
DECLARE @TAB TABLE (ID INT, STRVAL1 VARCHAR(8), STRVAL2 VARCHAR(8), BVAL1 BIT, BVAL2 BIT)
INSERT INTO @TAB VALUES
(1, NULL, NULL, NULL, NULL)
, (2, '', NULL, NULL, NULL)
, (3, '', '', NULL, NULL)
, (4, 'VAL', 'VAL', NULL, NULL)
, (5, 'VAL1', 'VAL2', NULL, NULL)
, (6, NULL, NULL, 0, NULL)
, (7, NULL, NULL, 0, 0)
, (8, NULL, NULL, 1, 1)
, (9, NULL, NULL, 1, 0)
SELECT ID, STRVAL1, STRVAL2, BVAL1, BVAL2
FROM @TAB
您可以只使用比较,尽管 NULL
使这有点麻烦:
select t.*
from @tab t
where ((strval1 <> strval2) or
(strval1 is null and strval2 is not null) or
(strval1 is not null and strval2 is null)
) or
((bval1 <> bval2) or
(bval1 is null and bval2 is not null) or
(bval1 is not null and bval2 is null)
);
您需要组合测试。
select ... from ... where
(strval1 is null and strval2 is not null) or
(strval1 is not null and strval2 is null) or
(strval1 != strval2) or
(bval1 is null and bval2 is not null) or
(bval1 is not null and bval2 is null) or
(bval1 != bval2)