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

前端 未结 7 2308
被撕碎了的回忆
被撕碎了的回忆 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:23

    Here is how you can solve this using a single WHERE clause:

    WHERE (@myParm = value1 AND MyColumn IS NULL)
    OR  (@myParm = value2 AND MyColumn IS NOT NULL)
    OR  (@myParm = value3)
    

    A naïve usage of the CASE statement does not work, by this I mean the following:

    SELECT Field1, Field2 FROM MyTable
    WHERE CASE @myParam
        WHEN value1 THEN MyColumn IS NULL
        WHEN value2 THEN MyColumn IS NOT NULL
        WHEN value3 THEN TRUE
    END
    

    It is possible to solve this using a case statement, see onedaywhen's answer

提交回复
热议问题