I have a SQL query written by a colleague who is no longer here. The request is executed as part of an SSIS job, and from this month a failure has occurred with the following error:
Converting a varchar data type to a datetime data type resulted in an out-of-range value.
The query itself is just a basic choice with a where clause that looks for values ββin a specific time range (date range between @startdate and @enddate )
Code for determining the time range below:
DECLARE @RunDateTime datetime DECLARE @RunDate datetime DECLARE @StartDate datetime DECLARE @EndDate datetime DECLARE @Month int DECLARE @Year int DECLARE @strStartDate varchar(10) SET @RunDateTime = GetDate() SET @RunDate = cast(round(convert(real, @RunDateTime),0,1) as datetime) IF DATEPART(d, @RunDate) = 16 BEGIN SET @StartDate = DATEADD(d, -15, @RunDate) SET @EndDate = @RunDate END ELSE BEGIN IF Month(@RunDate) = 1 SET @Month = 12 ELSE SET @Month = Month(@RunDate) - 1 IF Month(@RunDate) = 1 SET @Year = Year(@RunDate) - 1 ELSE SET @Year = Year(@RunDate) SET @strStartDate = CONVERT(varchar(2), @Month)+ '/16/' + CONVERT(varchar(4), @Year) SET @StartDate = CONVERT(datetime, @strStartDate, 101) SET @EndDate = @RunDate END
This work is done twice a month. Once on the 16th for data from the 1st to the 15th month and once on the 1st of the next month for data from the 16th to the end of the previous month.
From what I can find on the Internet, is using varchar for strStartDate the likely culprit? I'm not good enough with SQL to know how to replace everything that converts everything that happens there? Also, is there a better way to determine the end date of a month than just get the lead time? Any help at all would be greatly appreciated.
(PS, we run this task on SQL Server 2008 R2) And I checked with the database administrator and he did not say anything about the localization or regional settings that were changed on the SQL server.
source share