简体   繁体   中英

SQL CASE WHEN in WHERE clause

searched for this problem, but couldn't find a question for exactly this problem. I have a stored procedure that fetches data from a large amount of tables. In my SP I have a parameter indicating the ID. Default Value of that ID is zero. I want to return all values regarding this parameter in my query, unless a value is provided.

SELECT mT.*
FROM myTable mT
     (various JOINS)
WHERE 
CASE @myParameter
     WHEN 0 THEN 1 = 1
     ELSE mT.ID = @myParameter
END

Unfortunately I get the error message "Incorrect syntax near '='". Things that are fixed: It has to be a SP, I get just one parameter where I can set a default value in case it is not filled. If it is not filled this part of the where clause shall not apply (there are more statements in the WHERE clause.

If I did not see a question that contained this problem please give me a hint where to find it.

Best Regards and thanks in advance!

You don't need CASE :

SELECT mT.*
FROM myTable mT
     (various JOINS)
WHERE 
@myParameter= 0 OR mT.ID = @myParameter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM