Home » General

CASE Statement in Where Clause – Microsoft SQL

15 June 2009 2,558 views No Comment

Can we use CASE statement in a where clause? Answer is yes.

The way it works is like this:

SELECT * FROM myTable
WHERE col1 = CASE WHEN col2 < col3 THEN col2
ELSE col3
END

Another example:

I wanna check if a column matches an ID variable, @itemId, in the where clause. If @itemId has a positive value we return the matching rows that have that itemId, otherwise we return all rows. How I do that?

declare @itemId int;

select * from Items
Where
ItemId=CASE When @itemId>0 THEN @itemId ELSE itemId END;

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.