Search code examples
sqlsql-servercastingnullisnull

How to use null value IN operator SQL


I have a problem with column [Transfer-from Code].
There is like 30 different values.
But I need all values for [Transfer-from Code] which are x1, x2 and NULL.

Here is the code:

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'
*/

Can someone tell me where is my mistake?


Solution

  • Your condition should be:

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

    Check for NULLs only with the operators IS and IS NOT.
    Never with = or IN because the result of a comparison to NULL is always NULL.