Click here to Skip to main content
15,904,877 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How to use CASE and IF together in SQL..
Posted
Updated 19-Feb-15 23:16pm
v2
Comments
Wendelius 20-Feb-15 4:02am    
Which database, Sql Server, Oracle, Access, MySql...
CHill60 20-Feb-15 5:15am    
Don't SHOUT - all capitals is considered shouting on the internet and rude. It also makes you look childish.

You haven't stated what database you are using.

Here are links to the documentation for case expressions for MSSQL and Oracle.

... hope it helps.
 
Share this answer
 
The thing to be careful of here is ... do you mean can I use a CASE statement and an IF statement together? For example in a Stored Procedure?

The answer to that is "Yes", for example this sql is perfectly valid (if meaningless)
SQL
DECLARE @temp int
DECLARE @dt date
DECLARE @res VARCHAR(10)
SET @temp = 3
SET @dt = '03-JAN-2015'
IF @temp = 3 
BEGIN
	set @res = CASE WHEN @dt = '01-JAN-2015' 
                   THEN 'Bank Holiday' ELSE 'Go to work' END
	PRINT @res
END

CASE can also be used as a clause in a sql select statement for example
SQL
SELECT CASE WHEN DATENAME(dw, recDate) = 'Friday' THEN 'Leave early'
            WHEN DATENAME(dw, recDate) = 'Monday' THEN 'Groan'
            ELSE 'Go to work' END
FROM CP1

However, the IF statement cannot be used in the same way, so if the question is can I use a CASE clause and an IF clause in the same statement the answer is "No". For example the following SQL will generate an error
SELECT IF DAY(recDate = 6)  'Leave early' END FROM CP1

It is possible to use IIF in a where clause - see this blog[^] but on the whole I would personally stick to CASE
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900