Friday, September 7, 2012

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

 
doggy steps
doggy steps