Checking an input param if not Null and using it i

2019-02-01 18:20发布

What is the best way to include an input param in the WHERE clause but exclude it if it is null?

There are a number of ways I believe, but I can't seem to remember then.

Also could I use the COALESCE()? But I think this is only for SELECTing values?

Edit

To clarify, let's say a variable called @code ="1" then my where would be Where type='B' AND code = @code but if @code is null then I only want Where type='B' - notice the missing code = @code.

7条回答
对你真心纯属浪费
2楼-- · 2019-02-01 19:11

Here's another approach

SELECT * FROM Thingies WHERE ( @thingId IS NULL OR ThingID = @thingId )

If your parameter is NULL, the rest of the OR expression won't be evaluated.

查看更多
登录 后发表回答