开发者

Creating a T-sQL where clause to accept NULL values

开发者 https://www.devze.com 2023-02-27 08:09 出处:网络
Now I am developing a stored proc which takes 3 input parameters.开发者_StackOverflowBut the challenge is that the customer doesn\'t have to enter any of these parameters; they may instead have these

Now I am developing a stored proc which takes 3 input parameters.开发者_StackOverflow But the challenge is that the customer doesn't have to enter any of these parameters; they may instead have these 3 as nulls. How can I write this into the WHERE clause?

pseudocode is something like:

WHERE (@p1 = a.p1 or @p1 = '') 
and (@p2 = a.p2 or @p2 = '') 
and (@p2 = a.p2 or @p2 = '')

The above logic works when they choose all 3 parameters, but otherwise it returns 0 records.


It looks like you're checking for blank/empty string (meaning 'skip this'). If the variable is also nullable, perhaps use an ISNULL(x,'') to force the null argument to be converted to an empty string.

 WHERE (@p1 = a.p1 or ISNULL(@p1,'') = '')
 AND (@p2 = a.p2   or ISNULL(@p2,'') = '') 
 AND (@p2 = a.p2   or ISNULL(@p2,'') = '')


Try this:

  WHERE (@p1 = a.p1 or @p1 = '' OR @p1 IS NULL) 
    AND (@p2 = a.p2 or @p2 = '' OR @p2 IS NULL) 
    AND (@p2 = a.p2 or @p2 = '' OR @p3 IS NULL)


you should change the query to something like this:

WHERE (a.p1 = IsNull(NullIf(@p1, ''), a.p1))  
  and (a.p2 = IsNull(NullIf(@p2, ''), a.p2))
  and (a.p3 = IsNull(NullIf(@p3, ''), a.p3))
0

精彩评论

暂无评论...
验证码 换一张
取 消