SQL CASE WHEN …AND

2019-08-03 15:28发布

问题:

Is there a way to write a SQL query like this:

CASE WHEN DATEPART(yy,@year_end) = 2013 AND DATEPART(mm,@year_end) = 3         
        THEN @AdjStartYear = '2012/07/01' AND @AdjEndYear = '2012/12/31'

Basically, I want 2 things to happen after the CASE statement is evaluated.

Thanks

回答1:

No, you have to make 2 case statements

select @AdjStartYear = CASE WHEN DATEPART(yy,@year_end) = 2013 AND DATEPART(mm,@year_end) = 3
                            THEN  '2012/07/01' 
                       END,
       @AdjEndYear = CASE WHEN DATEPART(yy,@year_end) = 2013 AND DATEPART(mm,@year_end) = 3
                          THEN  '2012/12/31' 
                     END


回答2:

You could do it without the CASE statement:

SELECT @AdjStartYear = '2012/07/01', @AdjEndYear = '2012/12/31'
WHERE DATEPART(year, @year_end) = 2013 AND DATEPART(month, @year_end) = 3

This only performs the operation if the WHERE criteria is met. sqlFiddle