I have the following piece of inline SQL that I run from a C# windows service:
UPDATE table_name SET status_cd = '2', sdate = CAST('03/28/2011 18:03:40' AS DATETIME), bat_id = '33acff9b-e2b4-410e-baaf-417656e3c255', cnt = 1, attempt_date = CAST('03/28/2011 18:03:40' AS DATETIME) WHERE id = '1855'
When I run this against a SQL Server database from within the application, I get the following error:
System.Data.SqlClient.SqlException: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.
But if I take the piece of SQL and run it from SQL Management Studio, it will run without issue.
Any ideas what may be causing this issue?
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. You need separators for the date like a “/”, a “.” or a “-“. We use substring to concatenate the “-” to use an acceptable date format and then we use the CONVERT function to convert the characters to sql date.
Answer: The error is due to an invalid date format being saved to the custom_rmh_rooms_history SQL table. To resolve this issue, the Windows Regional settings need to be modified and the Short Date format needs to be in MM/dd/yyyy format.
Using the CONVERT() function to convert datetime to string VARCHAR is the first argument that represents the string type. datetime is an expression that evaluates to date or datetime value that you want to convert to a string. sytle specifies the format of the date.
Short Answer This can happen if you do not initialize a value to a DateTime field; the field does not accept NULL values, and it's a value type, so the default value of the non-nullable DateTime type will be used. Setting the value fixed it for me!
Ambiguous date formats are interpreted according to the language of the login. This works
set dateformat mdy select CAST('03/28/2011 18:03:40' AS DATETIME)
This doesn't
set dateformat dmy select CAST('03/28/2011 18:03:40' AS DATETIME)
If you use parameterised queries with the correct datatype you avoid these issues. You can also use the unambiguous "unseparated" format yyyyMMdd hh:mm:ss
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With