2016-03-03 116 views
0

我想弄清楚为什么我的case语句不起作用。可能有些简单。在代码下面出错。我不用w/SQL太多太多。T-SQL - 关键字'case'附近的语法不正确

case month(getdate()) 
    when '1' then 
     select 
      '[email protected]' as EmailAddress, 
      '[email protected]' as SubscriberKey, 
      sum(case when isclaimed = 0 then 1 else 0 end) as 'RemainingActiveCouponCodes' 
     from january_sms_welcome_codes 
    when '2' then 
     select 
      '[email protected]' as EmailAddress, 
      '[email protected]' as SubscriberKey, 
      sum(case when isclaimed = 0 then 1 else 0 end) as 'RemainingActiveCouponCodes' 
     from february_sms_welcome_codes 
end 

enter image description here

+0

查询的* rest *在哪里?如果您收到关于“case”的投诉,这意味着它在一个它不应该使用的地方使用。 BTW'CASE'用于* SQL语句中,它*不能*包含语句。你想用C语言中的'switch'来使用它吗? –

+0

Then Part你正在返回这么多的项目,它可以返回一列但不是多个 – TheGameiswar

+0

另外考虑试图从一个不同的表中选择基于一些标准是*不会*执行速度快于查询所有表,并使用'联盟所有'。这只会导致产生一个非效率的执行计划。事实上,如果每个表都有一个具有适当约束的“月份”列。 SQL Server可以选择适当的表来自行搜索 –

回答

3

的情况是返回一个值,而不是自己的一份声明中表达。换句话说:

declare @@month int 
set @@month=month(getdate()) 
if @@month=1 begin 
    select 
     '[email protected]' as EmailAddress, 
     '[email protected]' 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 
     '[email protected]' as EmailAddress, 
     '[email protected]' as SubscriberKey, 
     sum(case when isclaimed = 0 then 1 else 0 end) as 'RemainingActiveCouponCodes' 
    from february_sms_welcome_codes 
end 
相关问题