This is a problem one of our developers brought to me. He stumbled across an old stored procedure which used ‘WHERE col = NULL’ several times. When the stored procedure is executed it returns data.
If the query inside the stored procedure is executed manually it will not return data unless the ‘WHERE col = NULL’ references are changed to ‘WHERE col IS NULL’.
Can anyone explain this behavior?
That’s by design: if you compare anything to
null, it evaluates tounknown. Any logic withunknownis itselfunknown. So any statement withanything = nullwill always be false.The important difference is between these two constructs:
So:
So as you can see,
unknowntaints an entire expression.Based on the comments, a better answer would probably be checking for ANSI_NULLs, with:
If this returns
false, the= nullconstruct would work likeis null:The default is
ansi_nulls onthough, and it’s very unusual to see it turned off. A stored procedure does remember the setting from the time it was created:You can check the saved settings by scripting the procedure from SSMS.