如何将SQL Server 2008中的varchar时间转换为时间
问题描述:
我有decimal
时间,我可以转换成time
。不过,我需要插入转换后的时间到一具有time
数据类型的列的表如何将SQL Server 2008中的varchar时间转换为时间
DECLARE @hours decimal(15,4)
SELECT @hours = 20.5 //20 Hrs and 30 mins
SELECT
RIGHT('00' + CONVERT(varchar(2), FLOOR(@hours)), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((@hours - FLOOR(@hours)) * 60))), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((@hours - FLOOR(@hours)) * 60) - FLOOR(((@hours - FLOOR(@hours)) * 60))) * 60), 2) AS Time
这是我需要插入值到我的临时表:
create table #timetest(timetest time)
insert into #timetest
SELECT
RIGHT('00' + CONVERT(varchar(2), FLOOR(@hours)), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((@hours - FLOOR(@hours)) * 60))), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((@hours - FLOOR(@hours)) * 60) - FLOOR(((@hours - FLOOR(@hours)) * 60))) * 60), 2)
我得到这个错误:
Conversion failed when converting date and/or time from character string.
请帮我
答
declare @hours decimal(15,4)
set @hours = 20.5 --20 Hrs and 30 mins
create table #timetest(timetest time(0))
insert into #timetest(timetest) values(cast(@hours/24 as datetime))
select * from #timetest
drop table #timetest
结果:
20:30:00
答
我相信你不能有012对于超过24小时个值....
Range 00:00:00.0000000 through 23:59:59.9999999
更新:,如果你已经改变了你的时间少于24小时,你可以这样做插入:
create table #timetest(timetest time)
insert into #timetest(timetest)
SELECT
CAST(RIGHT('00' + CONVERT(varchar(2), FLOOR(@hours)), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((@hours - FLOOR(@hours)) * 60))), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((@hours - FLOOR(@hours)) * 60) - FLOOR(((@hours - FLOOR(@hours)) * 60))) * 60), 2) AS TIME)
你需要明确CAST
您的字符串AS TIME
,然后一切都应该工作得很好。
+0
是的你是对的。我也改变了我的时间 – Somashekhar 2012-07-27 10:00:55
我相信你不能有超过24个小时.... – 2012-07-27 09:51:47
你可以做''投值TIME'(@小时/ 24日期时间)'但'28.5'会给你时间'04:30:00.0000000',这不是我想要的。 – 2012-07-27 09:55:26
是的你是对的。我也改变了我的时间 – Somashekhar 2012-07-27 10:01:19