只在同一列中的日期和时间--sql server

时间:2013-10-23 07:01:19

标签: sql sql-server sql-server-2008

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

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做到这一点? btw我的专栏“dossier_date_created”的数据类型为datetime

3 个答案:

答案 0 :(得分:5)

您可以使用CASTCONVERT将您的值设为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 DEMO

编辑 - 对于2008年之前的SQL Server版本,没有DATE和TIME数据类型 - 您也可以直接CONVERTVARCHAR using appropriate style codes

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 DEMO

答案 1 :(得分: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

希望它会对你有所帮助.. :)

答案 2 :(得分: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

希望有所帮助:)

欢呼声......