Select all if parameter is null in stored procedure Select all if parameter is null in stored procedure sql sql

Select all if parameter is null in stored procedure


The common approach is:

WHERE C.Id = @company          AND S.Created >= @from         AND S.Created <= @to AND  (@serie_type IS NULL OR S.Type = @serie_type)


There is no need to do AND (@serie_type IS NULL OR S.Type = @serie_type) as SQL Server has a built in function to do this logic for you.

Try this:

   .   .   AND  S.Type = isnull( @serie_type, S.Type)

This returns

true if @serie_type is null or the result of @serie_type = S.Type if @serie_type is not null.

From the MSDN:

IsNull Replaces NULL with the specified replacement value.

ISNULL ( check_expression , replacement_value )

The value of check_expression is returned if it is not NULL; otherwise, replacement_value is returned after it is implicitly converted to the type of check_expression, if the types are different.


You can also use case statement in the where clause

where e.ZoneId = case when @zoneid=0 then e.zoneid else @zoneid end