2012-07-27 144 views
1

我有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.

請幫我

+1

我相信你不能有超過24個小時.... – 2012-07-27 09:51:47

+0

你可以做''投值TIME'(@小時/ 24日期時間)'但'28.5'會給你時間'04:30:00.0000000',這不是我想要的。 – 2012-07-27 09:55:26

+0

是的你是對的。我也改變了我的時間 – Somashekhar 2012-07-27 10:01:19

回答

0
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 
3

我相信你不能有012對於超過24小時個值....

檢查MSDN documentation on TIME

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

相關問題