ISNULL usage with NULL database fields
-
12-11-2019 - |
题
I am trying to do something that should be fairly simple but ISNULL isn't doing what I thought it would.
Basically I have a stored procedure and I am expecting either PARAM1 OR PARAM2 to have a matching value in my table.
SELECT * FROM MyTable WITH (NOLOCK)
WHERE
field1 = ISNULL(@PARAM1 ,field1 )
AND
field2 = @PARAM2
This works fine until I have NULL fields in my row then it excludes those results. Is there a different method that can cater for this?
解决方案
ISNULL replaces the first value with the second value, so only if your parameter @PARAM1 is NULL does it replace it with PARAM1. I assume you're not passing in NULL values, so that's probably not what you want. More likely you just want to say
WHERE
(Field1 = @PARAM1 OR Field1 IS NULL)
AND
Field2 = @Param2
I Suppose you could use ISNULL in this fashion too:
ISNULL(Field1, @PARAM1) = @PARAM1
其他提示
null is special in sql. If you do any comparisons on a column any rows that have a null for that column will be excluded.
SELECT * FROM MyTable WITH (NOLOCK)
WHERE
(PARAM1 = @PARAM1 or PARAM1 is null)
AND
(PARAM2 = @PARAM2 or PARAM2 is null)
Use
field1 = ISNULL(@PARAM1, A_REPLACEMENT_VALUE_IF_PARAM1_IS_NULL)
This will evaluate to-
field1 = @PARAM1 if @PARAM1 IS NOT NULL.
field1 = A_REPLACEMENT_VALUE_IF_PARAM1_IS_NULL if @PARAM1 IS NULL
EDIT:
Try these:
--If you want to ignore the WHERE clause if PARAM1/2 is null
ISNULL(field1, DEFAULT_VALUE) = ISNULL(@PARAM1, ISNULL(field1, DEFAULT_VALUE))
OR
ISNULL(field2, DEFAULT_VALUE) = ISNULL(@PARAM2, ISNULL(field2, DEFAULT_VALUE))
OR
--To get all rows with field1/2 as PARAM1/2 and ignore everything else
field1 = @PARAM1 OR field2 = @PARAM2