Reputation: 27
I have the following condition in my stored procedure:
[DMO].[DriverModelName] =
CASE WHEN ISNULL(@driverModelName,'NotSet') = 'NotSet' THEN
[DMO].[DriverModelName]
ELSE
@driverModelName
END
This implies that when I pass 'NotSet'
to varchar
parameter @driverModelName
, it should return all the rows but for some reason it's returning only those rows which has a value in column DriverModelName
& omitting the null
value rows.
Am I doing anything wrong here?
Upvotes: 0
Views: 67
Reputation: 31879
This is because NULL == NULL = FALSE
, for the purpose of the WHERE
clause, unless you set ANSI_NULLS
to OFF
. Example:
SET ANSI_NULLS OFF
IF NULL = NULL
PRINT 'TRUE'
ELSE
PRINT 'FALSE'
SET ANSI_NULLS ON
IF NULL = NULL
PRINT 'TRUE'
ELSE
PRINT 'FALSE'
The result is:
TRUE
FALSE
In order to get all rows, including the NULL
values, you should use
(@driverModelName IS NULL OR [DMO].[DriverModelName] = @driverModelName)
For references:
Additional Reading on Catch-All queries:
Upvotes: 2
Reputation: 12847
Well if [DMO].[DriverModelName]
is ever NULL
what are you expecting the result of this CASE
be? Isn't this missing a ISNULL()
around that column too?
ISNULL([DMO].[DriverModelName], 'NotSet') =
CASE WHEN ISNULL(@driverModelName,'NotSet') = 'NotSet' THEN
[DMO].[DriverModelName]
ELSE
@driverModelName
END
You cant say NULL = @someValue, it must be IS NULL
or handle both sides with ISNULL()
Upvotes: 0