我希望得到两个日期之间的天数差异。我在Sql中尝试过DateDiff函数,但它不适用于日期时间值,即
27/12/2013 8:53:00 PM
我尝试了以下查询,但它一直给我这个错误
"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value "
declare @StartDate datetime, @EndDate datetime
select @StartDate = '27/12/2013 08:53:00.000',@EndDate='10/04/2012 09:52:48.000'
SELECT DATEDIFF(day,@StartDate,@EndDate) AS DiffDate
任何帮助?在此先感谢
答案 0 :(得分:2)
1)为什么会出现该错误:“将varchar数据类型转换为日期时间数据类型会导致超出范围的值”?
原因解释为here:
日期时间支持的字符串文字格式
数字[0] 4/15 / [19] 96 - (mdy),...,15 / [0] 4 / [19] 96 - (dmy),...
描述SET DATEFORMAT的设置确定日期值的方式 被解释。
因此,使用DATEFORMAT设置将此字符串文字27/12/2013 8:53:00 PM
解释为DATETIME值。
示例:
DECLARE @CurrentDateFormat NVARCHAR(3);
SELECT @CurrentDateFormat = s.date_format FROM sys.dm_exec_sessions s WHERE s.session_id = @@SPID;
PRINT 'Test #1:'
SET DATEFORMAT DMY;
DECLARE @a DATETIME;
SET @a = '27/12/2013 8:53:00 PM';
PRINT @a;
PRINT 'End of Test #1';
PRINT 'Test #2:'
SET DATEFORMAT MDY;
DECLARE @b DATETIME;
SET @b = '27/12/2013 8:53:00 PM';
PRINT @b;
PRINT 'End of Test #2';
SET DATEFORMAT @CurrentDateFormat;
输出:
Test #1:
Dec 27 2013 8:53PM
End of Test #1
Test #2:
Msg 242, Level 16, State 3, Line 14
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
End of Test #2
2)解决方案?使用DATEFORMAT设置独立的字符串文字格式。您可以在同一web page上找到这些格式。
ODBC格式示例:
DECLARE @CurrentDateFormat NVARCHAR(3);
SELECT @CurrentDateFormat = s.date_format FROM sys.dm_exec_sessions s WHERE s.session_id = @@SPID;
PRINT 'Test #1:'
SET DATEFORMAT DMY;
DECLARE @a DATETIME;
SET @a = {ts '2013-12-27 16:53:00'};
PRINT @a;
PRINT 'End of Test #1';
PRINT 'Test #2:'
SET DATEFORMAT MDY;
DECLARE @b DATETIME;
SET @b = {ts '2013-12-27 16:53:00'};
PRINT @b;
PRINT 'End of Test #2';
SET DATEFORMAT @CurrentDateFormat;
输出:
Test #1:
Dec 27 2013 4:53PM
End of Test #1
Test #2:
Dec 27 2013 4:53PM
End of Test #2
3)这些格式仅确定[string literal]值如何被解释为DATETIME
值。内部格式/表示形式为here。
4)
DECLARE @StartDate DATETIME, @EndDate DATETIME
SELECT @StartDate = {ts '2013-12-27 08:53:00.000'},
@EndDate = {ts '2012-04-10 09:52:48.000'}
SELECT DATEDIFF(day,@StartDate,@EndDate) AS DiffDat
答案 1 :(得分:0)
这有效
declare @StartDate datetime, @EndDate datetime
select @StartDate = 'dec 27 2013 08:53:00.000',@EndDate='apr 10 2012 09:52:48.000'
SELECT DATEDIFF(day,@StartDate,@EndDate) AS DiffDate
答案 2 :(得分:0)
这应该让你开始:
declare @dt as datetime2;
declare @s as varchar(25), @dtstring as varchar(30);
select @s = '27/12/2013 08:53:00.00';
select @dtstring = substring(@s, 7, 4) + '-' +
substring(@s, 4, 2) + '-' +
left(@s, 2) + ' ' + substring(@s, 12, 12);
select @dt = cast(@dtstring as datetime2(4));
select @s ori, @dtstring modified, @dt result;
结果是:
ori modified result
27/12/2013 08:53:00.00 2013-12-27 08:53:00.00 2013-12-27 08:53:00.0000000
对你的两个字符串做同样的事情。顺便说一句,在您的问题中,您的开始日期晚于结束日期。不确定这是不是你的意图。