Question

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!

Was it helpful?

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.

OTHER TIPS

Execute the following on each new database connection.

SET DATEFORMAT DMY

After you do this, your problem should disappear. I suspect that your issue is conditioned by a combination of server locale, and whether the day-of-month is 13th to 31st or not.

Not only that you see the error, you may also be fetching data for incorrect periods without noticing; other layers of your software may be correcting for that, but maybe only in some cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top