2013-03-14 18 views
1

我已經搜索了這個,但我的字符串似乎與我可以找到的示例格式不同。在SQL Server 2008中字符串到時間

我有時間設置爲nvarchar(50)和值,如1535

我有兩個這些列,我想比較這兩個發現有多少分鐘的差別。如何將字符串轉換爲一次?

+0

我假定1535將是3:35 PM,是正確的? – 2013-03-14 11:47:11

+0

是你的值4位數字隨時? – 2013-03-14 11:47:59

+0

是的,這是正確的 – user1295053 2013-03-14 11:48:09

回答

2

單程;

declare @t1 nvarchar(4) = '1535' 
declare @t2 nvarchar(4) = '1700' 

select 
    datediff(minute, 
      cast(stuff(@t1, 3, 0, ':') as time), 
      cast(stuff(@t2, 3, 0, ':') as time)) 

>>85 
1

假設所有的值可以轉換爲Time

DECLARE @val1 as NVARCHAR(50); 
DECLARE @val2 as NVARCHAR(50); 
SET @val1 = '1535'; SET @val2 = '1655'; 

SELECT DATEDIFF(minute,convert(time,LEFT(@val1,2)+':'+RIGHT(@val1, 2)+':00'), CONVERT(time,LEFT(@val2,2)+':'+RIGHT(@val2, 2)+':00')) 
+0

從字符串中轉換日期和/或時間時轉換失敗。 – user1295053 2013-03-14 12:09:55

+0

我可以想象的是,因爲你有不適合轉換爲時間的值,因爲這是:2400 – 2013-03-14 12:16:49

+0

這是,謝謝你的幫助。 – user1295053 2013-03-14 13:09:54

1

If you need the difference in minutes,這是一個方法without converting你的價值觀to Datetime

假設所有nvarchar values are convertible to int他們在24h format差異c2-c1 in Minutes

Fiddle demo here

select ((c2*1-c1*1)/100)*60 + (c2*1-c1*1)%100 inMinutes 
from t 
相關問題