I am facing issue when trying to handle null.
Here is example
I have a table
Create table Test_Table
(
id int null,
pName varchar(10)
)
GO
Id column has NULL
value.
INSERT INTO Test_Table
SELECT NULL, 'A' UNION
SELECT NULL,'B' UNION
SELECT NULL, 'C' UNION
SELECT NULL,'D'
GO
Now when I execute different select statements, last two conditions are failing. I can use ISNULL
to handle it but there are approx 500 SPs which I would need to change.
So, I need solution apart from that, if possible.
SELECT * FROM Test_Table WHERE id is NULL --True
SET ANSI_NULLS OFF
SELECT * FROM Test_Table WHERE id=NULL --True
SET ANSI_NULLS OFF
SELECT * FROM Test_Table WHERE id=id --False. Why???
Declare @ID INT = 0
SET ANSI_NULLS OFF
Select case when @ID > 0 then @ID else id end as Statements, *
From Test_Table
Where ID = case when @ID > 0 then @ID else ID END -- Fails. Why??
When Id=NULL is true then why Id=Id is false??
Thanks!
Best Answer
Have a look at remarks on MS Docs about IS NULL:
And at SET ANSI_NULLS MS Docs:
Let me add some other records to your table:
Now, your query:
Returns:
And the same for your second query:
Null indicates lack of value and you must explicitly check for NULL values using IS NULL:
dbfiddle here