Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

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?

like image 790
amateur Avatar asked Mar 28 '11 23:03

amateur


People also ask

When converting a VARCHAR data type to a datetime data type the value is out of range?

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.

How do you fix the conversion of a VARCHAR data type to a datetime data type resulted in an out of range value in SQL?

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.

Can we convert datetime to VARCHAR?

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.

How do you solve the conversion of a datetime2 data type to a datetime data type resulted in an out of range value?

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!


1 Answers

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

like image 81
Martin Smith Avatar answered Oct 06 '22 01:10

Martin Smith