在SQL Server中格式化short int to time

时间:2014-06-09 18:32:59

标签: sql-server sql-server-2005

我的时间列显示为int80008:00am13001:00pm

如何格式化int以使其显示为12小时,例如1:13 pm

我正在使用SQL Server。

由于

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作以获得所需的结果。取自How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

的想法
set @time = 1300

select (@time / 1000000) % 100 + ':' +
       (@time / 10000) % 100  + ':' +
       (@time / 100) % 100  + ':' +
       (@time % 100) * 10 

答案 1 :(得分:0)

将整数转换为hh:mm:ss representation of datetime并处理表示层中的格式(即AM / PM):

DECLARE @Time INTEGER = 800;
SELECT
-- convert datetime to hh:mm:ss
CONVERT(VARCHAR,
        -- cast hh:mm to datetime
        CAST(-- insert semicolon to get hh:mm format
             STUFF(-- convert integer to string and pad with zeroes
                   RIGHT(REPLICATE('0', 4) + CAST(@Time AS VARCHAR), 4),
                   3, 0, ':')
        AS DATETIME),
        108);

SELECT @Time = 1300;
SELECT CONVERT(VARCHAR, CAST(STUFF(RIGHT(REPLICATE('0', 4) + CAST(@Time AS VARCHAR), 4), 3, 0, ':') AS DATETIME), 108);

从临时表中选择的示例:

CREATE TABLE #Time ( TimeValue INTEGER );
INSERT INTO #Time VALUES (800);
INSERT INTO #Time VALUES (1300);

SELECT CONVERT(VARCHAR,
               CAST(STUFF(RIGHT(REPLICATE('0', 4) + CAST(TimeValue AS VARCHAR), 4),
                          3, 0, ':')
                    AS DATETIME), 108) AS Time
FROM #Time;
DROP TABLE #Time;