格式函数在SQL Server 2008 R2中不起作用

时间:2017-10-18 03:22:50

标签: sql-server-2008-r2

我正在尝试在SQL 2008 R2中运行下面的脚本,但是我收到错误(FORMAT is not recognized)。我认为安装的SQL Server是2008 R2。有没有想过将脚本转换为在SQL Server 2008 R2中工作?提前谢谢。

declare @sample table (dt datetime)

insert @sample values ('2017-10-09 20:04:00.000')
insert @sample values ('2017-10-07 00:55:22.000')
insert @sample values ('2017-10-16 15:52:34.000')
insert @sample values ('2017-10-06 03:09:31.000')
insert @sample values ('2017-10-06 19:56:09.000')
insert @sample values ('2017-10-06 06:36:39.000')
insert @sample values ('2017-10-05 16:19:14.000')

select 
    s.dt,
    DATEADD(hh,8,s.dt) AS dt_plus_8,
    FORMAT(CAST(DATEADD(HH,8,s.dt) AS DATETIME), 'hh tt') as TIME_HOURLY
from
    @sample s

期望的结果:

DT----------------------DT_Plus_8--------------Tim_Hourly
----------------------------------------------------------
2017-10-09 20:04:00.000--2017-10-10 04:00:00.000--04 AM
2017-10-07 00:55:22.000--2017-10-07 08:00:00.000--08 AM
2017-10-16 15:52:34.000--2017-10-16 23:00:00.000--11 PM
2017-10-06 03:09:31.000--2017-10-06 11:00:00.000--11 AM
2017-10-06 19:56:09.000--2017-10-07 03:00:00.000--03 AM
2017-10-06 06:36:39.000--2017-10-06 14:00:00.000--02 PM
2017-10-05 16:19:14.000--2017-10-06 00:00:00.000--12 AM

1 个答案:

答案 0 :(得分:0)

这对你有用吗<​​/ p>

SELECT  
    s.dt,
    DATEADD(HOUR,8,s.dt) AS dt_plus_8,
    FORMAT(CAST(DATEADD(HH,8,s.dt) AS DATETIME), 'hh tt') as TIME_HOURLY
    ,RIGHT('00' + CONVERT(VARCHAR,DATEPART(HOUR, DATEADD(HOUR,8,s.dt)) % 12 ),2) 
        + ' ' 
            + CASE WHEN DATEPART(HOUR, DATEADD(HOUR,8,s.dt)) > =12 
                THEN 'PM' 
                ELSE 'AM' 
              END AS TIME_HOURLYv2
FROM
    @sample s