SQL ignore part of WHERE if parameter is null

后端 未结 7 610
既然无缘
既然无缘 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:52

    You can use use COALESCE() function in SQL server. You don't need to use IF- Else or CASE in your statements. Here is how you can use COALESCEfunction.

    SELECT Id, col1, col2, col3, col4 FROM myTable where col1 = COALESCE(NULLIF(@param1, ''), col1) and col2 = COALESCE(NULLIF(@param2, ''), col2) and col3 = COALESCE(NULLIF(@param3, ''), col3) and col4=
    COALESCE(NULLIF(@param4, ''), col4)
    

    The COALESCE function in SQL returns the first non-NULL expression among its arguments. Here for example if the @param1 is equal to null the function will return col1 which will lead to col1=col1 in the where statement which is like 1=1 meaning the condition will always be true.

    0 讨论(0)
提交回复
热议问题