Assign to a T-SQL variable from a CASE statement

References: http://stackoverflow.com/questions/6945979/assign-to-a-t-sql-variable-from-a-case-statement

The example you’ve given should work. You can assign to variables from a case statement. Just pretend that the entire CASE..WHEN..THEN..ELSE..END block is a field. Here is a generic example:

declare

@string1 nvarchar(100) = null

,@string2 nvarchar(100) = null

;

select top 1

@string1 = case when 1=1 then ‘yes’ else ‘no’ end

,@string2 = case when 1=0 then ‘yes’ else ‘no’ end

print ‘string1 = ‘ + @string1

print ‘string2 = ‘ + @string2

Gives:

string1 = yes

string2 = no

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s