0

我有一个门户网站,如果日期是今天的日期,它应该只显示时间,否则它应该显示 date 。

dossier_date_created       |   Expected result
----------------------------------------------------
2013-10-22 16:18:46.610    |     2013-10-22
2013-10-23 11:26:56.390    |     11:26

我试过这样的事情:

select 
case 
when CONVERT(date,dossier_date_created) = CONVERT(DATE,getdate()) then convert(char(5), dossier_date_created, 108) 
else convert(date, dossier_date_created) 
end as timedate
 from Proj_Manage_Dossier

但结果是:

     timedate
    -----------
    2013-10-22
    1900-01-01

我怎样才能只用 SQL 做到这一点?顺便说一句,我的列“dossier_date_created”的数据类型是datetime

4

3 回答 3

5

您可以使用CASTorCONVERT来获取您的值DATETIME数据类型。但是,由于您不能在同一列中组合两种数据类型,因此您必须将它们都转换为相同的东西 - 就像NVARCHAR之后:

SELECT CASE WHEN CAST(dossier_date_created AS DATE) = CAST(GETDATE() AS DATE) 
            THEN CAST(CAST (dossier_date_created AS TIME) AS NVARCHAR(10))
    ELSE CAST(CAST(dossier_date_created AS DATE) AS NVARCHAR(10)) END
FROM dbo.Proj_Manage_Dossier

SQLFiddle 演示

编辑- 对于 2008 年之前的 SQL Server 版本,其中没有 DATE 和 TIME 数据类型 - 您也可以直接CONVERT使用VARCHAR 适当的样式代码

SELECT CASE WHEN CONVERT(VARCHAR(10),dossier_date_created,102) = CONVERT(VARCHAR(12),GETDATE(),102)
            THEN CONVERT(VARCHAR(10),dossier_date_created,108)
    ELSE CONVERT(VARCHAR(10),dossier_date_created,102) END
FROM dbo.Proj_Manage_Dossier

SQLFiddle 演示

于 2013-10-23T07:08:01.033 回答
1

这对我来说很好:

    select 
      case 
      when (CONVERT(date,PaymentDate) = CONVERT(DATE,getdate()))
       then convert(VARCHAR(15), PaymentDate, 108) 
      else convert(varchar, PaymentDate, 101) 
      end as timedate
    from Payments

希望它会帮助你.. :)

于 2013-10-23T07:14:46.100 回答
0

这将起作用

select case when cast(dossier_date_created as date) = cast(getdate() as date) 
    then cast(cast(dossier_date_created as time) as varchar)
    else cast(cast(dossier_date_created as date) as varchar)
    end from #Proj_Manage_Dossier

希望能帮助到你 :)

干杯......

于 2013-10-23T09:22:16.667 回答