SQL ignore part of WHERE if parameter is null

后端 未结 7 615
既然无缘
既然无缘 2020-12-15 15:59

I have a stored procedure that fetches info from a table based on 4 parameters.

I want to get values based on the parameters, but if a parameter is NULL then that pa

7条回答
  •  情歌与酒
    2020-12-15 16:49

    This will work and easier to understand, at least for me. The IIF statement is only available in SQL Server 2012 and up, you can replace it with a case statement.

    SELECT Id, col1, col2, ... 
    FROM    myTable 
    WHERE   condition1 = IIF(col1 IS NULL, col1, @Param1)
    AND     condition2 = IIF(col2 IS NULL, col2, @Param2)...
    

提交回复
热议问题