Search code examples
sql-serverstored-proceduressql-server-2008-r2sqlexceptionoutofrangeexception

Is March 27th, 2012 of significance to SQL Server in a Varchar to Datetime conversion?


I have a stored procedure that takes a datetime parameter which is passed in as a string. Such as this:

Procedure:

CREATE PROCEDURE [dbo].[MyFancySP]
   @MyStartDate datetime = NULL,
   @MyEndDate datetime = NULL
AS
....

Call:

EXEC [dbo].[MyFancySP]
   @MyStartDate = N'01/01/2012',
   @MyEndDate = N'03/01/2012'

The stored procedure has been working like this forever. Now, here's the interesting part. As soon as I change the date to 03/27/2012 or past it, I get the following error: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

The only place in the stored procedure where the dates are used is in the where clause. In case it has to do with it, I'll copy it in here as well:

WHERE
((@MyStartDate IS NOT NULL AND @MyEndDate IS NOT NULL 
AND d.SomeDate >= @MyStartDate AND d.SomeDate <= @MyEndDate) 
OR @MyStartDate IS NULL AND @MyEndDate IS NULL)

Any ideas why I'm getting the out of range exception on March 27th or beyond? This is running on SQL Server 2008 R2 by the way.

Thanks!


Solution

  • What type is d.SomeDate? Is it a NVARCHAR by any chance? That would explain it, as the WHERE clause would contain in such case an implicit conversion that the rules of Data Type Precedence state that should occur as a DATETIME. The apparent randomness of the error occurs due to the simple fact that the query scans rows that have invalid dates in the d.SomeDate field. In such a case you're dealing with data purity issues and you should fix your tables, preferably by making the column a DATETIME.

    In addition:

    • always use the canonical date format YYYYMMMDD (no delimiters) in string representation: EXEC [dbo].[MyFancySP] N'20120101', N'20120301';. This format is independent of the host locale, DATEFORMAT and LANGUAGE settings, .

    • Read Dynamic Search Conditions in T-SQL. WHERE column=@value or @value is null stops query performance optimizations dead on its track. Read the article.