Reputation: 15734
I have a stored procedure that accepts an optional @ID param. When the param is passed in, I want the WHERE statement to include something like id = @ID, otherwise, when @ID is null, I don't want it to be filtered.
For example:
@ID BIGINT = NULL
SELECT * from myTable
WHERE
CASE
WHEN @ID IS NOT NULL THEN mytable.id = @ID
END
I am running this in SQL server 2016 and it says bad syntax near mytable.id = @ID. Can CASE be used in this way or should I try a different SQL method for this?
The only other option I considered to accomplish this was by using IF conditions in my stored procedure, but that didn't seem possible either based on my searches.
Upvotes: 0
Views: 510
Reputation: 33581
CASE is an expression, not a statement. It is not used to control flow like this and it will not work.
Your logic would need to be something like this.
Where mytable.id = ISNULL(@ID, mytable.id)
I should caution you that this pattern can lead to some poor performance. For a more detailed explanation and some other options you should check out this article. http://www.sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/
Upvotes: 4
Reputation: 63966
A bad-performance approach would be:
WHERE ISNULL(@ID,mytable.id) = mytable.id
A better-performance approach would be:
if(@ID IS NULL)
select * from ... without the WHERE condition
else
do your query with the condition mytable.id = @ID
Or build the query dynamically in the stored proc and execute it through sp_executesql
passing parameters
Note: If the table is small enough, stick to simplicity and use the first option.
Upvotes: 0