October 10, 2007 at 2:01 pm
Can a Case conditional statement be used outside of a select statement i.e. if I want to run a specific set of code depending on a parameter being sent something like this
declare @Value int
set @Value = 4
case @value = 1 then -- do something
.
.
case @value = 4 then -- do something
.
.
.
[n case statements]
Or is this conditional keyword only available imbedded in a select statement?
October 10, 2007 at 2:20 pm
CASE cannot be used in this manner.
you have to stick with IF..ELSE Statements
October 10, 2007 at 2:24 pm
Thanks Ray
October 11, 2007 at 1:16 am
But it is not a bad idea to use CASE with a SELECT prefix as such you are not going to lose any thing.
SELECT CASE WHEN @value = 1 THEN
DO Process
CASE WHEN @value = 2 THEN
DO Process
ELSE
Do someother process
END
It really matters what you are looking to accomplish in this process.
Prasad Bhogadi
www.inforaise.com
October 11, 2007 at 1:55 am
Prasad Bhogadi (10/11/2007)
But it is not a bad idea to use CASE with a SELECT prefix as such you are not going to lose any thing.SELECT CASE WHEN @value = 1 THEN
DO Process
CASE WHEN @value = 2 THEN
DO Process
ELSE
Do someother process
END
It really matters what you are looking to accomplish in this process.
Prasad
I'm sorry but I haven't come across this syntax before and it doesn't appear to work. This fails with a syntax error:
DECLARE @value int
set @value = 1
SELECT CASE WHEN @value = 1 THEN
PRINT 'Yes'
CASE WHEN @value = 2 THEN
PRINT 'No'
ELSE
PRINT 'Maybe'
END
whereas this works:
DECLARE @value int
set @value = 1
SELECT CASE WHEN @value = 1 THEN
'Yes'
WHEN @value = 2 THEN
'No'
ELSE
'Maybe'
END
You will notice that I've removed the second CASE from your code, and taken away the "commands" in the case statement. If you want to have conditional commands, then you do need to use IF...THEN...ELSE.
John
October 11, 2007 at 2:03 am
Hello John,
Thanks for pointing it out. It was my oversight to include CASE inbetween, sorry about that. I stand corrected.
Prasad Bhogadi
www.inforaise.com
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply