我在名为TimeZone的表中有两列Arrive_Date和Interval。我正在尝试添加这两列以获得第三列,其中包含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.
任何人都可以帮我吗?
答案 0 :(得分:2)
好吧,我不是在带有数据库引擎的计算机上,所以我无法测试它(我同意它们是丑陋的字符串操作),但这是一种方法:
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
答案 1 :(得分:1)
我会使用dateadd()
和数学操作数来完成工作。它应该更快。
select dateadd(minute,
Interval%100,
dateadd(hour,
CAST(Interval/100 as int),
Arrive_Date)
)
from TimeZone
答案 2 :(得分:0)
使用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
答案 3 :(得分:0)
我会使用一个计算列(并且我将“间隔”存储为从一天开始以秒为单位的所需偏移量(但这只是我):
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