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

avatar 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

avatar image

Piotr Rodak
262 2 4

(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

avatar image

Squirrel 1
1.6k 1 3 5

(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.

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:

x2076
x2018
x1066

asked: May 21, 2010 at 06:24 PM

Seen: 3185 times

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

Copyright 2016 Redgate Software. Privacy Policy