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
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 COALESCE
function.
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.