如果date为null(SQL Server CE)

时间:2013-02-28 16:23:00

标签: sql sql-server-ce

我正在尝试查询包含status列和DateSent列的表格。在我的查询中,我想将这两列合并到一个sent列中 - 如果状态为c(已关闭/已发送),则显示DateSent - 但如果不是,然后显示适当的状态。

任何不是sent的行都会将DateSent设为NULL。

下面的所需输出:

ID     Sent
-----------------
1      Queued
2      Failed
3      2013-02-28
4      Queued

我当前的SQL Server CE查询:

select 
    ID, DateAdded, 
    case when DateSent is null then 
      (case when Status='W' then 'Waiting' else 
       case when Status='O' then 'Uploaded' else 
       case when Status='F' then 'Failed' else 
       case when Status='E' then 'Expired' else 
       'Unknown' end end end end) else DateSent 
    end as Sent 
from table

但是第7行的else DateSent部分引发了错误:

  

日期格式中存在语法错误。 [0,0,0,表达式:失败,]

有人可以帮我解决这个问题吗?

编辑:问题的一个更容易阅读的片段是:

select case when DateSent is null
then 'null' else DateSent --<---- problem is here
end as Sent from table

1 个答案:

答案 0 :(得分:2)

试试这个; (您可能需要将DateSent转换为nvarchar)

 select ID, 
        DateAdded, 
        case when DateSent is null
             then (case status when 'W' then 'Waiting'  
                               when 'O' then 'Uploaded'  
                               when 'F' then 'Failed'  
                               when 'E' then 'Expired' 
                                        else 'Unknown' 
                   end)
             else  convert(nvarchar(30), DateSent) 
        end as Sent
from table