CASE equivalent of a nested IIF statement

前端 未结 4 850
暖寄归人
暖寄归人 2021-01-25 05:14

Can anyone please decode the following nested IIF to a CASE statement in SQL.. I know IIF is allowed in SQL Server 2012 but I find it hard to get an easy grasp of a nested IIF l

相关标签:
4条回答
  • 2021-01-25 05:53

    This is old now, and there are other answers that already work, but for fun it is possible to write this as a functional expression without any CASE statements at all, like this:

    char(65 + ceiling(ceiling(COALESCE(NULLIF(TABLE_A.Col_1, 0), TABLE_A.Col_2 + (2*TABLE_A.Col_3))) - .5 / 10000000000000))
    

    There is a very small chance that the functional approach will perform noticeably better on large sets with good indexing.

    Here's my proof-of-concept test script:

    http://sqlfiddle.com/#!3/a95b3/2

    0 讨论(0)
  • 2021-01-25 06:02
    CASE 
        WHEN 
         (CASE 
              WHEN TABLE_A.Col1= 0 
              THEN TABLE_A.Col2_2 + (2*TABLE_A.Col3)
              ELSE TABLE_A.Col1 
          END) <=0.5 
        THEN 'A'
        ELSE 'B'
    END
    AS result
    
    0 讨论(0)
  • 2021-01-25 06:07

    I think this is what it boils down to in one CASE expression:

    CASE
      WHEN TABLE_A.Col_1 = 0 AND TABLE_A.Col_2 + (2*TABLE_A.Col_3) <= .5 THEN 'A'
      WHEN TABLE_A.Col_1 <> 0 AND TABLE_A.Col_1 <= .5 THEN 'A'
      ELSE 'B'
    END
    
    0 讨论(0)
  • 2021-01-25 06:09

    This should be the equivalent:

    CASE
        WHEN
            CASE
                WHEN TABLE_A.Col_1 = 0
                THEN TABLE_A.Col_2 + (2*TABLE_A.Col_3)
                ELSE TABLE_A.Col_1
            END <= .5
        THEN 'A'
        ELSE 'B'
    END As Result
    
    0 讨论(0)
提交回复
热议问题