Issue
I have a query with hard coded dates, in this format
startdate >= '2012-11-03' AND enddate <= '2012-11-30 23:59'
My database date format is 'mdy', however I'm sure it will accept yyyy-mm-dd as its the universal date structure.
When I try run this query in SSMS on my target DB connected with a specific database user (userX) I get an error about the date formats
Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
However, when I run the exact query connected as the SA user, the query executes..
Why is this? I have given userX full dbo permissions (sysadmin etc) and still get the error?
Solution
If you need to specify datetimes using strings, you should use a safe, language-independent format.
In SQL Server, that's the ISO-8601 format (slightly adapted), and it supports basically two safe formats for DATETIME that always work - regardless of your language, regional and dateformat settings:
YYYYMMDD (e.g. 20121231 for 31st of December 2012) if you need date only
YYYY-MM-DDTHH:mm:ss (e.g. 2012-12-31T21:05:00 for 31st of December 2012, 9:05pm)
Note:
the first date-only format has no dashes or delimiters!
the second format has dashes for the date (can be omitted, too), and there's a fixed
Tas delimiter between the date and the time portion of the string
Update: as per your last comment (on the different default languages for the two users) - try this:
-- this is how your `SA` interprets the string as datetime....
SET LANGUAGE english
SELECT CAST('2012-11-30 23:59' AS DATETIME)
Works just fine...
-- this is how your British user interprets teh string as datetime
SET LANGUAGE british
SELECT CAST('2012-11-30 23:59' AS DATETIME)
Msg 242, Level 16, State 3, Line 7
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
This tries to interpret the string as 11th of the 30th month of 2012 and obviously, that fails....
Answered By - marc_s Answer Checked By - Willingham (sql.easybugfix Volunteer)
Post a Comment
Post a Comment