I am building some test scenarios for my application. In order to do this, I have some code that is generating some SQL to help me test properly. A sample of the SQL that is generated is shown here:
INSERT INTO MyTable
(
[ID],
[Name],
[CheckInDate],
[CheckOutDate]
)
VALUES
(
1,
'A title',
'Sat, 17 Dec 2011 14:33:12 GMT',
'Sat, 17 Dec 2011 15:13:12 GMT'
)
When I attempt to execute this SQL, I receive the following:
Conversion failed when converting date and/or time from character string.
How can i format the date/time strings so that SQL Server 2008 will accept them? I really need my C# code to generate the SQL (including the date/time items) to create my tests properly.
Thank you!
The way to solve this is to use the ISO-8601 date format that is supported by SQL Server – this format works always – regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDDfor just dates (no time portion) – note here: no dashes!, that’s very important!YYYY-MM-DDis NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!or:
YYYY-MM-DDTHH:MM:SSfor dates and times – note here: this format has dashes.This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 and the
DATEdatatype (onlyDATE– notDATETIME!), then you can indeed also use theYYYY-MM-DDformat and that will work, too, with any settings in your SQL Server.Don’t ask me why this whole topic is so tricky and somewhat confusing – that’s just the way it is. But with the
YYYYMMDDformat, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.