When a NULL is not a NULL
I've just come across a little logic flaw in a SQL construct I have relied on for some time. Needless to say I have some work ahead of me to find places I have used it and fixed it.
To keep my stored procedures tidy but still allow optional parameters (like CF can deliver by using CFIF around the extra WHERE clause), I have been using this type of thing:
FROM any_table
WHERE field_id = ISNULL(@field_id,field_id)
This code is supposed to work as follows - give me all rows where field_id in the row matches the passed in parameter @field_id but if the @field_id wasn't passed in was passed in as a NULL show all rows. It shows all rows because in all cases the field_id in the row should match itself, correct?
WRONG! If field_id is actually a NULL value then the row becomes WHERE NULL = NULL. I just ran some tests and was baffled but then remembered the rules of three valued LOGIC (where there are three possible values of true, false or NULL) - NULL compared to anything is always an unknown value. This article gives it a good wrap:
After realizing my mistake the code now looks like this to achieve the same effect but correctly:
FROM any_table
WHERE field_id = @field_id OR @field_id IS NULL
Hope that helps someone.