SQL 可能有 NULL 值的多个 NOT LIKE

SQL Multiple NOT LIKE with possible NULL values

我正在尝试从多个不同于“%1%”、“%2%”和“%3%”的字段中提取数据

但是,这些字段中的一个或多个容易为 NULL,这导致它们在结果中被忽略。我也想要 NULL 值的结果。我看到 data1 = 5、data2 = 6 和 data3 为 NULL 并且这些记录未返回的实例。

这是我的查询:

WHERE
region = 'AZ' and
year(date) = '2014' and

data1 not like '%1%' and
data2 not like '%1%' and
data3 not like '%1%' and

data1 not like '%2%' and
data2 not like '%2%' and
data3 not like '%2%' and

data1 not like '%3%' and
data2 not like '%3%' and
data3 not like '%3%'

在末尾添加一个 OR 子句

WHERE
region = 'AZ' and
year(date) = '2014' and
(
data1 not like '%1%' and
data2 not like '%1%' and
data3 not like '%1%' and

data1 not like '%2%' and
data2 not like '%2%' and
data3 not like '%2%' and

data1 not like '%3%' and
data2 not like '%3%' and
data3 not like '%3%'
OR data1 IS NULL OR data2 IS NULL OR data3 IS NULL
)

我找到了解决方法。我打开了一个测试 table,将所有 NULL 值转换为“0”,然后 运行 我的查询。它看起来像这样:

Drop table #test
Select
region
, data1
, data2
, data3
into #test

from YourTable

Where
region = 'AZ' and
year(date) = '2014' and
data1 is NULL or 

region = 'AZ' and
year(date) = '2014' and
data2 is NULL or 

region = 'AZ' and
year(date) = '2014' and
data3 is NULL or

--------

UPDATE [#test] SET [data1] = 0 WHERE [data1] IS NULL
UPDATE [#test] SET [data2] = 0 WHERE [data2] IS NULL
UPDATE [#test] SET [data3] = 0 WHERE [data3] IS NULL

--------

Select
region
, data1
, data2
, data3

from #test

Where
data1 not like '%1%' and
data2 not like '%1%' and
data3 not like '%1%' and

data1 not like '%2%' and
data2 not like '%2%' and
data3 not like '%2%' and

data1 not like '%3%' and
data2 not like '%3%' and
data3 not like '%3%'