Checking an input param if not Null and using it in where in SQL Server

后端 未结 8 1550
暖寄归人
暖寄归人 2020-12-23 14:05

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

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-23 14:10

    You can use ISNULL(), or check for nulls explicitly as others have mentioned. This should be OK as long as you have no more than 1 or 2 optional input parameters. But if there are more parameters, this approach would be very inefficient as the indexes you create on those columns won't be used as you would expect. In such a case i would recommend you to use dynamic SQL. Here is an excellent article that explains why http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/

提交回复
热议问题