[英]DateTime Conversion Error in T-SQL
我在名為TimeZone的表中有兩列Arrive_Date和Interval。 我試圖將這兩列添加到第三列將具有日期和間隔。
我的表有這樣的數據:
Interval Arrive_Date
830 2010-11-01 00:00:00.000
1100 2010-11-01 00:00:00.000
1230 2010-11-02 00:00:00.000
0 2011-01-04 00:00:00.000
30 2011-03-17 00:00:00.000
我想要第三列作為
Interval Arrive_Date Arrive_DateTime
830 2010-11-01 00:00:00.000 2010-11-01 08:30:00.000
1100 2010-11-01 00:00:00.000 2010-11-01 11:00:00.000
1230 2010-11-02 00:00:00.000 2010-11-02 12:30:00.000
0 2011-01-04 00:00:00.000 2011-01-04 00:00:00.000
30 2011-03-17 00:00:00.000 2011-03-17 00:30:00.000
我正在使用此查詢:
SELECT CAST(LEFT(CONVERT(VARCHAR,Arrive_DATE,101),10) + ' ' + LEFT(Interval,2) + ':' + RIGHT(Interval,2) + ':00' AS DATETIME)
from TimeZone
但我收到此錯誤:
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
誰可以幫我這個事?
好的,我不在帶數據庫引擎的計算機上,因此我無法對此進行測試(並且我同意它們是丑陋的字符串操作),但這是一種方法:
SELECT Interval, Arrive_Date,
CAST(CONVERT(VARCHAR(8),Arrive_Date,112) + ' ' + LEFT(RIGHT('0000'+CAST(Interval AS VARCHAR(4)),4),2)+':'+RIGHT('00'+CAST(Interval AS VARCHAR(4)),2)+':00' AS DATETIME) AS Arrive_Datetime
FROM TimeZone
我將使用dateadd()
和數學操作數來完成這項工作。 它應該更快。
select dateadd(minute,
Interval%100,
dateadd(hour,
CAST(Interval/100 as int),
Arrive_Date)
)
from TimeZone
使用DATEADD()代替這些難看的字符串操作怎么辦?
嘗試類似的方法:
SELECT
Interval % 100 AS [Minutes],
CONVERT(INT, Interval / 100) AS [Hours],
DATEADD(HOUR, CONVERT(INT, Interval / 100), DATEADD(MINUTE, Interval % 100, Arrive_Date)) AS [AllTogether]
FROM TimeZone
我將使用計算列(並且我將“間隔”存儲為與從開始日期起數秒的期望偏移量(但這就是我):
drop table #TimeZone
go
create table #TimeZone
(
id int not null identity(1,1) primary key ,
interval_hhmm int not null ,
Arrive_Date datetime not null ,
Arrive_DateTime as dateadd( mm , interval_hhmm % 100 , -- add the minutes
dateadd( hh , interval_hhmm / 100 , -- add the hours
convert(datetime,convert(varchar,Arrive_Date,112),112) -- make sure the base date/time value doesn't have a time component
)
) ,
)
go
insert #TimeZone ( interval_hhmm , Arrive_Date ) values(830 , '2010-11-01 23:59:59.000')
insert #TimeZone ( interval_hhmm , Arrive_Date ) values(1100 , '2010-11-01 00:00:00.000')
insert #TimeZone ( interval_hhmm , Arrive_Date ) values(1230 , '2010-11-02 00:00:00.000')
insert #TimeZone ( interval_hhmm , Arrive_Date ) values(0 , '2011-01-04 00:00:00.000')
insert #TimeZone ( interval_hhmm , Arrive_Date ) values(30 , '2011-03-17 00:00:00.000')
select * from #timezone
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.