我有一个包含2列的表格
1. start_hr as smallint
2. Start_min as varchar(2)
我需要转换为时间怎么办
我也将其转换为varchar,然后尝试按时间进行转换,但没有成功
表名称:DateTime_Table
答案 0 :(得分:1)
为了实现这一目标,您可以:
TIME
TIME
转换为varchar
代码是:
SELECT start_hr, Start_min, LTRIM(CONVERT(VARCHAR(12), CONVERT( TIME, CONCAT(start_hr, ':', Start_min)), 22)) AS Output
FROM #DateTime_Table
这将输出:
start_hr Start_min Output
-------- --------- ------------
9 45 9:45:00 AM
13 25 1:25:00 PM
19 52 7:52:00 PM
23 12 11:12:00 PM
如果您急于摆脱秒针,则需要添加第五步:
更多代码:
SELECT start_hr,
Start_min,
CONCAT(LEFT(Output, LEN(Output) - 6), RIGHT(Output, 3)) AS Output
FROM (
SELECT start_hr, Start_min, LTRIM(CONVERT(VARCHAR(12), CONVERT( TIME, CONCAT(start_hr, ':', Start_min)), 22)) AS Output
FROM #DateTime_Table
) a
输出:
start_hr Start_min Output
-------- --------- ---------------
9 45 9:45 AM
13 25 1:25 PM
19 52 7:52 PM
23 12 11:12 PM
答案 1 :(得分:1)
您的查询如下:
select CAST(CONCAT(CONCAT(CAST(Start_hr as varchar),':'), Start_min) as time)
FROM DateTime_Table
在此处检查结果:sqlfiddle
答案 2 :(得分:0)
如果您使用SQL Server 2012+,则可以尝试使用TIMEFROMPARTS()
函数返回完全初始化的时间值:
数据:
CREATE TABLE #Data (
start_hr smallint,
start_min varchar(2)
)
INSERT INTO #Data
(start_hr, start_min)
VALUES
(9, '45'),
(12, '1'),
(23, '18')
声明:
SELECT
TIMEFROMPARTS(start_hr, CONVERT(numeric(2, 0), start_min), 0, 0, 0) AS TimeValue,
CONVERT(varchar, TIMEFROMPARTS(start_hr, CONVERT(numeric(2, 0), start_min), 0, 0, 0), 109) AS ConvertValue
FROM #Data
输出:
TimeValue ConvertValue
09:45:00 9:45:00AM
12:01:00 12:01:00PM
23:18:00 11:18:00PM
答案 3 :(得分:0)
尝试如下
SELECT
CONVERT(varchar, DATEADD(s, start_hr * 60*60+start_min*60, 0), 108)
from table_name