将nvarchar数据类型转换为日期时间数据类型会导致超出范围的值 - 闰年

时间:2013-02-20 15:05:21

标签: sql

我在存储过程代码中收到此错误,我发现其中一条记录来自闰年日期2008-02-29。如何使用我的代码解决这个问题。这是代码:

set @ContractDate = cast(cast(@Year as nvarchar(4))
+ '/' + cast(datepart(mm,@ContractDate) as nvarchar(2))
+ '/' + cast(datepart(dd,@ContractDate) as nvarchar(2)) as datetime)

3 个答案:

答案 0 :(得分:2)

首先关闭:

  • 您对@Year和@ContractDate有什么价值?
  • @ContractDate的格式/类型是什么?

我问,因为这适用于我us_english SQL Server 2012

SELECT cast('2008/02/29' as datetime)

但是,如果我更改SET DATEFORMAT,那么我可以打破上面的代码

-- breaks
SET DATEFORMAT DMY;
SELECT cast('2008/02/29' as datetime)

使用ISO日期格式是OK 无论我用于SET DATEFORMAT

SET DATEFORMAT DMY;
SELECT cast('20080229' as datetime);
SET DATEFORMAT MDY;
SELECT cast('20080229' as datetime);
SET DATEFORMAT YDM;
SELECT cast('20080229' as datetime);

结论:您使用的是非ISO日期格式并依赖于隐式转换

答案 1 :(得分:0)

最好在转换为datetime / date之前以ISO格式(yyyymmdd)获取字符串,并且无论文化设置如何,它都可以在任何服务器中使用

如果@ContractDate datetime/date 类型且@year类似于 2012/'2012' ,则应遵循以下规则。 Working Example

Set @ContractDate = convert(datetime,
  convert(varchar(4),@year) + right(convert(varchar(8),@ContractDate,112),4))

答案 2 :(得分:0)

ALTER PROCEDURE [dbo].[Sden_report1]
@fromdt nvarchar(13),
@todt nvarchar(13)

AS

BEGIN 
select AD_PID,AD_Appointmentdate,AD_Patientname,AD_Patientphno,AD_Visitpurpose
from Appointment_Details1
where 
--PL_CID = @CID and PL_Itemcode = @JCode AND
(@fromdt = '' OR (DATEDIFF(DAY,AD_Appointmentdate, @fromdt) <= 0))
AND (@todt = '' OR (DATEDIFF(DAY,AD_Appointmentdate, @todt) >= 0))
end


GO

When i Execute the procedure
i will get below error:

EXEC Sden_report1 '20-11-2012','20-05-2013'

Error
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.

Anyone Help...`enter code here`