在select查询中使用多个case语句

时间:2013-10-26 20:11:48

标签: sql sql-server

您好我有以下查询检查代码以确定何时输入或查看。

        declare @timestamp datetime;
        select
          case @timestamp
          when a.updatedDate =1760 then 'Entered on' +a.updatedDate
          when a.updatedDate=1710 then  'Viewed on' +a.updatedDate
          else 'Last Updated on'+ a.updatedDate
          end 
         from t_mainTable a
         where a.id=@Id;

当我尝试运行此查询时,它会给我错误

Msg 102, Level 15, State 1, Procedure p_xxxx, line 40
Incorrect syntax near '='.   

when行中有一些syntex错误。请让我知道如何纠正这个问题 谢谢

1 个答案:

答案 0 :(得分:19)

有两种方法可以编写case语句,你似乎正在使用两者的组合

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

是等价的。它们可能无法工作,因为您可能需要将日期类型转换为varchars以将它们附加到其他varchars。