Under the covers, Simple CASE
expressions are evaluated as searched CASE
expressions. That is,
CASE @foo
WHEN 1 THEN 'a'
WHEN 2 THEN 'b'
is actually evaluated as
CASE
WHEN @foo = 1 THEN 'a'
WHEN @foo = 2 THEN 'b'
In most situations the difference is inconsequential, but when the input expression isn’t fixed, for instance if RAND()
is involved,
it is likely to yield unexpected results. For that reason, it is better to evaluate the input expression once, assign it to a variable, and use the
variable as the CASE
's input expression.
This rule raises an issue when any of the following is used in a CASE
input expression: RAND
, NEWID
,
CRYPT_GEN_RANDOM
.
Noncompliant code example
CASE CONVERT(SMALLINT, RAND()*@foo) -- Noncompliant
WHEN 1 THEN 'a'
WHEN 2 THEN 'b'
Compliant solution
DECLARE @bar SMALLINT = CONVERT(SMALLINT, RAND()*@foo)
CASE @bar
WHEN 1 THEN 'a'
WHEN 2 THEN 'b'