SQL ignore part of WHERE if parameter is null

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

    How about something like

    SELECT Id, col1, col2, col3, col4 
    FROM    myTable 
    WHERE   col1 LIKE @Param1+'%'
    OR      @Param1 IS NULL
    

    in this specific case you could have also used

    SELECT Id, col1, col2, col3, col4 
    FROM    myTable 
    WHERE   col1 LIKE ISNULL(@Param1,'')+'%'
    

    But in general you can try something like

    SELECT Id, col1, col2, col3, col4 
    FROM    myTable 
    WHERE   (condition1 OR @Param1 IS NULL)
    AND     (condition2 OR @Param2 IS NULL)
    AND     (condition3 OR @Param3 IS NULL)
    ...
    AND     (conditionN OR @ParamN IS NULL)
    

提交回复
热议问题