CASE Statement SQL: priority in cases?

I have a general question when you use the CASE statement in SQL (Server 2008), and more than one of the WHEN conditions is true, but the resulting flag should be different.

This is a hypothetical example, but can be passed when applying checks on multiple columns to classify data in rows. The result of the code below depends on how the cases are ordered, since both values ​​are true.

DECLARE @TESTSTRING varchar(5)
SET @TESTSTRING = 'hello'

SELECT CASE 
WHEN @TESTSTRING = 'hello' THEN '0'
WHEN @TESTSTRING <> 'hi' THEN '1'
ELSE 'N/A' 
END AS [Output]

In general, would it be bad practice to create flags this way? Would a WHERE, OR clause be better?

+4
source share
2 answers

, . . , 0.

:

CASE:

  • Boolean_expression WHEN.
  • result_expression Boolean_expression, TRUE.
  • Boolean_expression TRUE, Database Engine else_result_expression, ELSE, NULL, ELSE.

, . ANSI, , :

select (case when val < 10 then 'Less than 10'
             when val < 100 then 'Between 10 and 100'
             when val < 1000 then 'Between 100 and 1000'
             else 'More than 1000' -- or NULL
        end) as MyGroup
+4

: SQL case/when, WHEN TRUE. :

SELECT 
    CASE 
        WHEN 3 = 3 THEN 3
        WHEN 4 = 4 THEN 4
    ELSE NULL 
    END AS test 

3, WHERE first, TRUE, .

0

Source: https://habr.com/ru/post/1534055/


All Articles