使用DateTime列的CASE语句

时间:2012-04-26 16:46:30

标签: sql tsql

我的查询中有一个datetime列,我想在此查询中执行CASE。

如果DateDelivered列不为null,则显示日期,否则,显示字符串' Pendent' 我怎么能这样做?

CASE WHEN DateDelivered IS NOT NULL THEN DateDelivered ELSE 'Pendent' END AS DateDelivered 2

我收到了这个错误

Conversion failed when converting date and/or time from character string.

整个查询

SELECT  San_Imovel.Imovel_Id ,
        San_Chave.DataHoraPegou ,
        CASE WHEN San_Chave.DateDelivered IS NOT NULL THEN San_Chave.DateDelivered
             ELSE ISNULL(CAST(San_Chave.DateDelivered AS VARCHAR), 'Pendent')
        END AS DateDelivered2 ,
        San_Usuario.NomeCompleto + ' - ' + sc.Apelido AS Nome ,
        San_Cliente.NomeCompleto AS NomeCliente ,
        San_Credenciada.Apelido ,
        San_Cliente.Cliente_Id ,
        San_ChaveImovel.QuantidadeChave
FROM    San_ChaveImovel
        JOIN San_Chave ON San_ChaveImovel.Chave_Id = San_Chave.Chave_Id
        JOIN San_Credenciada ON San_Chave.Credenciada_Id = San_Credenciada.Credenciada_Id
        JOIN San_Imovel ON San_ChaveImovel.Imovel_Id = San_Imovel.Imovel_Id
        JOIN San_Usuario ON San_Chave.Usuario_Id_Responsavel = San_Usuario.Usuario_Id
        JOIN San_Credenciada sc ON San_Usuario.Credenciada_Id = sc.Credenciada_Id
        JOIN San_Cliente ON San_Chave.Cliente_Id = San_Cliente.Cliente_Id  

2 个答案:

答案 0 :(得分:6)

您正在尝试将'Pendent'转换为DateTime,因为它会将所有数据转换为相同的数据类型。此外,如果您只是检查NULL,则可以使用ISNULL或COALESCE。试试这个:

ISNULL(CAST(DateDelivered AS VARCHAR), 'Pendent')

您还可以指定DateDelivered的格式:

ISNULL(CONVERT(VARCHAR, DateDelivered, 101), 'Pendent')

查看101 here的更多选项。

答案 1 :(得分:2)

CASE运算符返回的值与第一个结果子句的类型和大小相同。由于无法将“待定”转换为DateTime值,因此必须将日期值转换为其varchar表示形式:

CASE WHEN DateDelivered IS NOT NULL THEN CONVERT(VARCHAR(10), DateDelivered, 120)
ELSE 'Pendent'
END AS DateDelivered 

在此示例中,您可以使用ISNULL

获得相同的结果
ISNULL(CONVERT(VARCHAR(10), DateDelivered, 120), 'Pending') AS [DateDelivered]

注1:将日期值转换为varchar时,我总是更喜欢YYYY-MM-DD顺序,因为它不是一个模糊的格式。

注意2:请注意,当根据第一个结果子句的大小截断varchar值时,误用CASE会导致更微妙的错误:

CASE WHEN 1=0 THEN 'A'
ELSE 'BBB'
END -- returns only 'B' !!!