2010-05-01 54 views
1

我正在使用db(SQL Server 2008),並且存儲在db中的時間有一個有趣的問題。鑄造奇數smallint時間到日期時間格式

最初設置它的DBA是狡猾的,並以12小時的形式存儲在smallint中的計劃時間 - 上午6:00將表示爲600.我已經計算出如何將它們分成幾小時和幾分鐘:

select floor(time/100) as hr, right(time, 2) as min from table; 

我想要做的是將這些計劃時間與實際時間進行比較,這些時間以適當的日期時間格式存儲。理想情況下,我會在兩個日期時間字段之間執行此操作,並在它們之間使用datediff(),但這需要將smallint時間轉換爲datetime,這是我無法弄清楚的。

有沒有人有如何做到這一點的建議?

在此先感謝。

回答

1

可以想出兩種方法來做到這一點。首先是建立HH:MM格式的字符串,並將其轉換爲datetime。第二種是將smallint格式轉換爲float,其天數爲單位。天數是內部時間表示,因此您可以將其轉換爲datetime

示例代碼:

declare @i smallint 
set @i = 621 

-- Cast to a string '6:21', then to a datetime 
select cast(CAST(@i/100 as varchar) + ':' + CAST(@i % 100 as varchar) 
    as datetime) 

-- Convert to number of days, which is the interal datetime format 
select cast((@i/100)/24.0 + (@i%100)/(24*60.0) as datetime) 

P.S.如果你用另一個整數除整數。結果是第三個整數:100/24 = 4。如果用浮點數除整數,則結果爲浮點數:100/24.0 = 4.16666

+0

謝謝,我喜歡這一個的簡單,和它的作品。一個小小的絆腳石:因爲我的數據被儲存在12個小時的格式,我需要運行兩個查詢,否則我會得到一個錯誤(消息241:語法錯誤從字符串轉換日期時間)。將數據分割成00:00至11:59和12:00至23:59工作。 – 2010-05-02 22:51:02

1

由於您使用的是SQL Server 2008,因此您可以利用新的Time數據類型。爲了將整數轉換爲時間值,我們需要假設最後兩位數字是分鐘。要獲得分鐘部分,除以100,取整數部分並從初始值中減去它。因此,在621的情況下,我們得到:

621 - Floor(621/100)* 100 
621 - Floor(6.21)*100 
621 - 6*100 
621 - 600 = 21 minutes 

的小時部分,我們可以簡單地把整數值100。

Create Table #Test(IntVal smallint not null) 
Insert #Test Values(621) 
Insert #Test Values(2359) 
Insert #Test Values(1200) 
Insert #Test Values(1201) 
Insert #Test Values(1159) 

Select Z.TimeVal, GetDate(), DateDiff(hh, Z.TimeVal, Cast(GetDate() As Time(0))) 
From (
     Select Cast(DateAdd(mi 
        , IntVal - Floor(IntVal/100)*100 
        , DateAdd(hh, Floor(IntVal/100), 0) 
        ) As Time(0)) As TimeVal 
     From #Test 
     ) As Z 

部分這裏的伎倆劃分後使用DateAdd(hh, Floor(IntVal/100), 0)哪些針對datetime的零值執行DateAdd