Case conditional statement

  • 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?

  • CASE cannot be used in this manner.

    you have to stick with IF..ELSE Statements

  • Thanks Ray

  • 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

  • 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

  • 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