x

Problem with CASE Statement in T-SQL

Hello Everyone,

I am a beginner trying to learn T-SQL and here is where I was stuck. Can anyone please help me out with this.

use AdventureWorks go

declare @n as int =1

n = CASE

when n=1 then print('n=1')

when n=2 then print ('n=2')

print ('that implies n>1')

when n=2+2 then print('n=4')

else

print('n is some other value.')

end

Thankyou very much.....It would be of great help !!

more ▼

asked May 21, 2010 at 06:24 PM in Default

pragathi gravatar image

pragathi
1 1 1 2

(comments are locked)
10|1200 characters needed characters left

2 answers: sort voted first

You can't mix assignment with output in CASE statement.

You can print the output basing on the value of the @n variable using following syntax for example:

declare @n int             
set @n = 1            
            
print CASE            
    when @n=1 then 'n=1'            
    when @n=2 then 'n=2'            
    when @n=2+2 then 'n=4'            
    else            
    'n is some other value.'            
end            

Please note that each time you use variable it must be prefixed with @ and print statement contains conditional expression that determines what has to be printed. Alternatively, you can assign the output of case statement to a variable and print it:

declare @n int, @msg varchar(50)             
set @n = 1            
            
set @msg = CASE            
        when @n=1 then 'n=1'            
        when @n=2 then 'n=2'            
        when @n=2+2 then 'n=4'            
        else            
        'n is some other value.'            
    end            
            
print @msg            

When you assign a value to a variable, you have to use keyword set or select, depending on the situation.

Regards

Piotr

more ▼

answered May 21, 2010 at 10:05 PM

Piotr Rodak gravatar image

Piotr Rodak
262 2

(comments are locked)
10|1200 characters needed characters left

you should be using IF . . ELSE for flow control not CASE .. WHEN

CASE .. WHEN is to use within a QUERY

more ▼

answered May 21, 2010 at 08:59 PM

Squirrel 1 gravatar image

Squirrel 1
1.6k 1 3

Thankyou so much guys... It was really helpful !!
May 24, 2010 at 11:13 AM pragathi
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x1950
x1842
x987

asked: May 21, 2010 at 06:24 PM

Seen: 2406 times

Last Updated: May 21, 2010 at 06:24 PM