WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

前端 未结 7 2290
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 22:57

I have a stored procedure in SQL Server 2000 that performs a search based on parameter values. For one of the parameters passed in, I need a different WHERE cla

7条回答
  •  渐次进展
    2020-12-02 23:18

    I've had success with this solution. It's almost like Patrick's, with a little twist. You can use these expressions separately or in sequence. If the parameter is blank, it will be ignored and all values for the column that your searching will be displayed, including NULLS.

    SELECT * FROM MyTable
    WHERE 
        --check to see if @param1 exists, if @param1 is blank, return all
        --records excluding filters below
    (Col1 LIKE '%' + @param1 + '%' OR @param1 = '')
    AND
        --where you want to search multiple columns using the same parameter
        --enclose the first 'OR' expression in braces and enclose the entire 
        --expression 
    ((Col2 LIKE '%' + @searchString + '%' OR Col3 LIKE '%' + @searchString + '%') OR @searchString = '')
    AND
        --if your search requires a date you could do the following
    (Cast(DateCol AS DATE) BETWEEN CAST(@dateParam AS Date) AND CAST(GETDATE() AS DATE) OR @dateParam = '')
    

提交回复
热议问题