T-SQL - 关键字' case'附近的语法不正确

时间:2016-03-03 16:27:22

标签: tsql

我试图找出我的case声明无效的原因。可能是简单的事情。代码下面的错误。我的工作量太差了太多。

case month(getdate())
    when '1' then
        select 
            'mmarks@fd.com' as EmailAddress, 
            'mmarks@fd.com' as SubscriberKey, 
            sum(case when isclaimed = 0 then 1 else 0 end) as 'RemainingActiveCouponCodes' 
        from january_sms_welcome_codes
    when '2' then
        select 
            'mmarks@fd.com' as EmailAddress, 
            'mmarks@fd.com' as SubscriberKey, 
            sum(case when isclaimed = 0 then 1 else 0 end) as 'RemainingActiveCouponCodes' 
        from february_sms_welcome_codes
end

enter image description here

1 个答案:

答案 0 :(得分:3)

CASE是一个表达式,它返回一个值,而不是一个语句。改写如下:

declare @@month int
set @@month=month(getdate())
if @@month=1 begin
    select 
        'mmarks@fd.com' as EmailAddress, 
        'mmarks@fd.com' as SubscriberKey, 
        sum(case when isclaimed = 0 then 1 else 0 end) as 'RemainingActiveCouponCodes'
    from january_sms_welcome_codes
end
if @@month=2 begin
    select 
        'mmarks@fd.com' as EmailAddress, 
        'mmarks@fd.com' as SubscriberKey, 
        sum(case when isclaimed = 0 then 1 else 0 end) as 'RemainingActiveCouponCodes' 
    from february_sms_welcome_codes
end