如何使用空值 IN 运算符 SQL

How to use null value IN operator SQL

我对 [Transfer-from Code] 列有疑问。
大约有 30 个不同的值。
但是我需要 [Transfer-from Code] 的所有值,它们是 x1、x2 和 NULL。

代码如下:

SELECT 
       ILE.[Item No_]           AS ItemNo
      ,It.[Tariff No_]          AS TariffNo
      ,ILE.[Posting Date]       AS PostingDate
      ,ILE.[Location Code]      AS LocationCode
      ,ILE.[Quantity]           AS Qty
      ,CASE 
       WHEN ILE.[Entry Type] = 0 THEN 'Purchase'    
       WHEN ILE.[Entry Type] = 4 THEN 'Transfer'
       ELSE '' END AS EntryType
      ,Trp.[Transfer-from Code] AS SourceLocation
      -- Try to cast from below all NULL values to be test, so I can use them into IN operator. Still not working
      --,ISNULL(Trp.[Transfer-from Code], 'test') AS SourceLocation

FROM [MDR].[dbo].[nav_XX$Item_Ledger_Entry]             AS ILE 
LEFT JOIN [MDR].[dbo].[nav_XX$Item]                     AS It ON ILE.[Item No_] = It.No_
LEFT JOIN [MDR].[dbo].[nav_XX$Transfer_Receipt_Header]  AS Trp on ILE.[Document No_] = Trp.No_

WHERE ILE.[Entry Type] IN ('0','4')
AND ILE.[Posting Date] > '2019-12-11 00:00:00.000'
AND ILE.[Location Code] IN ('X24','XB16')

--From this part below, everything don't work. I'm getting only the values for X1 and X2.

--AND TRP.[Transfer-from Code] IN ('X1','X2',NULL)

--AND TRP.[Transfer-from Code] IN ('X1','X2','test')

/*
AND TRP.[Transfer-from Code] = 'X1'
OR TRP.[Transfer-from Code] = 'X2'
--OR TRP.[Transfer-from Code]= NULL
OR TRP.[Transfer-from Code]= 'test'
*/

谁能告诉我哪里错了?

您的条件应该是:

AND (TRP.[Transfer-from Code] IN ('X1','X2') OR TRP.[Transfer-from Code] IS NULL)

仅使用运算符 ISIS NOT.
检查 NULL 永远不要使用 =IN 因为与 NULL 比较的结果总是 NULL.

Null特殊含义代表未知,无所谓 等。这就是为什么它有 特殊语法 来检查:

 field IS NULL

你的情况

 (field IN (item1, item2, item3) OR field IS NULL)

例如

 (TRP.[Transfer-from Code] IN ('X1', 'X2') OR TRP.[Transfer-from Code] IS NULL)

请注意,即使文字像

 field = NULL

 field IN (null)

语法正确,当field是[=]时,结果既不是true也不是false而是NULL 18=](是的,NULL = NULL 不是 true):

if field with unknown value (Null) equals to some other unknown value (Null)? It's unknown (Null)

"="替换为"IS",添加"()"即可。

尝试:

AND 
(
    TRP.[Transfer-from Code] = 'X1'
    OR TRP.[Transfer-from Code] = 'X2'
    OR TRP.[Transfer-from Code] IS NULL
)