How do I use T-SQL's Case/When?

后端 未结 4 517
广开言路
广开言路 2020-12-13 17:09

I have a huge query which uses case/when often. Now I have this SQL here, which does not work.

 (select case when xyz.something = 1
 then
     \'SOM         


        
相关标签:
4条回答
  • 2020-12-13 17:50

    As soon as a WHEN statement is true the break is implicit.

    You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.

    More information here: break in case statement in T-SQL

    0 讨论(0)
  • 2020-12-13 17:56
    declare @n int = 7,
        @m int = 3;
    
    select 
        case 
            when @n = 1 then
                'SOMETEXT'
        else
            case 
                when @m = 1 then
                    'SOMEOTHERTEXT'
                when @m = 2 then
                    'SOMEOTHERTEXTGOESHERE'
            end
        end as col1
    -- n=1 => returns SOMETEXT regardless of @m
    -- n=2 and m=1 => returns SOMEOTHERTEXT
    -- n=2 and m=2 => returns SOMEOTHERTEXTGOESHERE
    -- n=2 and m>2 => returns null (no else defined for inner case)
    
    0 讨论(0)
  • 2020-12-13 18:03
    SELECT
       CASE 
       WHEN xyz.something = 1 THEN 'SOMETEXT'
       WHEN xyz.somethingelse = 1 THEN 'SOMEOTHERTEXT'
       WHEN xyz.somethingelseagain = 2 THEN 'SOMEOTHERTEXTGOESHERE'
       ELSE 'SOMETHING UNKNOWN'
       END AS ColumnName;
    
    0 讨论(0)
  • 2020-12-13 18:04

    If logical test is against a single column then you could use something like

    USE AdventureWorks2012;  
    GO  
    SELECT   ProductNumber, Category =  
          CASE ProductLine  
             WHEN 'R' THEN 'Road'  
             WHEN 'M' THEN 'Mountain'  
             WHEN 'T' THEN 'Touring'  
             WHEN 'S' THEN 'Other sale items'  
             ELSE 'Not for sale'  
          END,  
       Name  
    FROM Production.Product  
    ORDER BY ProductNumber;  
    GO  
    

    More information - https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017

    0 讨论(0)
提交回复
热议问题