I’m trying to assign values contained in a lookup table to multiple variables by using a single SELECT having multiple CASE statements.
The table is a lookup table with two columns like so:
[GreekAlphabetastic]
SystemID Descriptor
-------- ----------
1 Alpha
2 Beta
3 Epsilon
This is my syntax:
SELECT
@VariableTheFirst =
CASE
WHEN myField = 'Alpha' THEN tbl.SystemID
END,
@VariableTheSecond =
CASE
WHEN myField = 'Beta' THEN tbl.SystemID
END,
@VariableTheThird =
CASE
WHEN myField = 'Epsilon' THEN tbl.SystemID
END
FROM GreekAlphabetastic tbl
However, when I check the variables after this statement executes, I expected each to be assigned the appropriate value, but instead only the last has a value assigned.
SELECT
@VariableTheFirst AS First,
@VariableTheSecond AS Second,
@VariableTheThird AS Third
Results:
First Second Third
NULL NULL 3
What am I doing wrong?
The first 2 variables are being reset to null after being assigned. i.e. when it hits the Epsilon record, the first 2 variables are being assigned to null as there is nothing to prevent that in the CASE statement.
So, try this: