您可以在T-SQL Case语句中休息一下吗?

时间:2018-10-22 18:18:46

标签: sql-server tsql case

在T-SQL中是否有一种用case语句检查逻辑的方法,如果某行满足条件,则它将不会为其余case语句评估该行。 (就像在C ++中一样)

例如:

Case When X is true Then scenario A
Case when Y is true Then scenario B
Case when Z is true Then scenario C

第1行-如果场景A是正确的(但也可能是场景B),我想发生的是,对于第一行,我们将行标记为A,并跳过对其余情况的评估。然后我们转到第2行,等等。

-我应该添加case语句进行更新-这是数据示例。

set [fixed_brand_new] =     
CASE WHEN   ((CustCount = 1 AND src.order_fix_or_flex = 'fx'))                                          
    OR                                                                                                                                                                          
    (CustCount > 2 AND src.order_fx_or_fl = 'fx' AND GapDiff2 is NULL)                   
    OR 
    (CustCount = 2 AND src.order_fx_or_fl  = 'fx' AND season_counter = MaxSeasonCounter AND GapDiff2 is NULL  )
THEN 'Y' ELSE '' END,

    [flex_brand_new] =          
CASE WHEN   ((CustCount = 1 AND src.order_fx_or_fl  = 'fl'))                                    
    OR
    (CustCount > 2 AND src.order_fx_or_fl  = 'fl'  AND GapDiff2 is NULL)                         
     OR 
    (CustCount = 2 AND src.order_fx_or_fl  = 'fl' AND src.season_counter = MaxSeasonCounter AND GapDiff2 is NULL  )                         
THEN 'Y' ELSE '' END,                                                               

1 个答案:

答案 0 :(得分:1)

CASE语句,当一起评估多个列时,首先返回要评估为TRUE的WHEN。此示例应演示其工作原理:

DECLARE @TestData TABLE
    (
        [X] BIT
      , [Y] BIT
      , [Z] BIT
    );

INSERT INTO @TestData (
                          [X]
                        , [Y]
                        , [Z]
                      )
VALUES ( 1, 1, 0 )
     , ( 0, 1, 1 )
     , ( 0, 1, 0 )
     , ( 0, 0, 1 );

SELECT *
     , CASE WHEN [X] = 1 THEN 'Scenario: A x=1 others don''t matter'
            WHEN [Y] = 1 THEN 'Scenario: B x=0 and y=1, what Z is doesn''t matter'
            WHEN [Z] = 1 THEN 'Scenario: C x=0 and y=0 and z=1'
       END EvaluateTogether
     , CASE WHEN [X] = 1 THEN 'Scenario A'
       END --Evalute each individual column as another column
     , CASE WHEN [Y] = 1 THEN 'Scenario B'
       END --Evalute each individual column as another column
     , CASE WHEN [Z] = 1 THEN 'Scenario C'
       END --Evalute each individual column as another column
FROM   @TestData;