rspec/rules/S4094/tsql/rule.adoc

59 lines
1.2 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,sql]
2021-04-28 16:49:39 +02:00
----
CASE CONVERT(SMALLINT, RAND()*@foo) -- Noncompliant
WHEN 1 THEN 'a'
WHEN 2 THEN 'b'
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,sql]
2021-04-28 16:49:39 +02:00
----
DECLARE @bar SMALLINT = CONVERT(SMALLINT, RAND()*@foo)
CASE @bar
WHEN 1 THEN 'a'
WHEN 2 THEN 'b'
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]