我有一个名为Data_Details的表,数据如下:
DateTimeClosed Datesub TimeSub
6/20/2011 18:00 5/16/2011 17:13:17
6/20/2011 18:00 5/18/2011 13:45:17
6/1/2011 19:00 5/24/2011 8:30:12
我试图在分钟内获得关闭日期和子日期之间的区别。
我写了这样的话:
SELECT convert(int,convert(Datetime,[DateTimeClosed])-
(convert(Datetime,[Datesub])+convert(datetime,[TimeSub])))*24*60
FROM dbo.Data_details
它给了我以下错误:
Msg 241,Level 16,State 1,Line 2 从字符串转换日期和/或时间时转换失败。
任何人都可以帮助我吗?
答案 0 :(得分:2)
以秒为单位返回时差:
select datediff(SECOND,'5/16/2011'+' '+'17:13:17','6/20/2011 18:00')
示例脚本:
declare @test as table
(
date1 datetime,
date2 date,
date3 time
)
insert into @test
values
('6/20/2011 18:00' , '5/16/2011' , '17:13:17')
select Datediff(second,cast (date2 as varchar)+' '+ cast(date3 as varchar),date1) from @test
更新 - 现在使用varchars,OP澄清它们都是varchars:
declare @test as table
(
date1 varchar(50),
date2 varchar(50),
date3 varchar(50)
)
insert into @test
values
('6/20/2011 18:00' , '5/16/2011' , '17:13:17')
select Datediff(second,cast (date2 +' '+date3 as datetime),cast (date1 as datetime)) from @test
答案 1 :(得分:0)
试试这个:
SELECT DATEDIFF(MINUTE,CONVERT(DATETIME,Datesub + ' ' + TimeSub,101),CONVERT(DATETIME,DateTimeClosed,101))
FROM yourTable
答案 2 :(得分:0)
我认为你正在寻找DateDiff
此示例将返回分钟:
SELECT DATEDIFF(m, CONVERT(datetime, [Datesub] + ' ' + [TimeSub]), CONVERT(datetime, [DateTimeClosed]))
FROM dbo.Data_details
答案 3 :(得分:0)
SET DATEFORMAT MDY
;with dates AS
(
SELECT '6/20/2011 18:00' as datetimeclosed,'5/16/2011' as datesub,'17:13:17' as timesub UNION ALL
SELECT '6/20/2011 18:00','5/18/2011','13:45:17' UNION ALL
SELECT '6/1/2011 19:00','5/24/2011','8:30:12'
)
SELECT
DATEDIFF(minute,CAST(datesub + ' ' + timesub AS DATETIME),CAST(datetimeclosed AS DATETIME)) as time_diff_in_minutes
FROM dates