I’ve had the same problem and determined that this issue arises because SQL Server does not perform comparisons on characters converted to integers in an identical manner. In my test, I’ve found that some comparisons of converted characters, such as the exclamation point, will return type conversion errors, while other comparisons of converted characters, such as the space, will be determined to be out of range.
This sample code tests the different possible scenarios and presents a solution using nested REPLACE statements. The REPLACE determines if there are any characters in the string that are not numerals or the slash, and, if any exist, the length of the string will be greater than zero, thereby indicating that there are ‘bad’ characters and the date is invalid.
DECLARE @str varchar(10)
SET @str = '12/10/2012'
IF convert(int, substring(@str,4,2)) <= 31 AND convert(int, substring(@str,4,2)) >= 1
PRINT @str+': Passed Test'
ELSE PRINT @str+': Failed Test'
GO
DECLARE @str varchar(10)
SET @str = '12/10/2012'
PRINT 'Number of characters in ' + @str + ' that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): ' + convert(varchar(5),len(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(@str,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''), '8',''),'9',''),'/',''),' ','+'))) --replace space with a + to avoid empty string
PRINT ''
GO
DECLARE @str varchar(10)
SET @str = '12/!0/2012'
IF convert(int, substring(@str,4,2)) <= 31 AND convert(int, substring(@str,4,2)) >= 1
PRINT @str+': Passed Test'
ELSE PRINT @str+': Failed Test'
GO
DECLARE @str varchar(10)
SET @str = '12/!0/2012'
PRINT 'Number of characters in ' + @str + ' that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): ' + convert(varchar(5),len(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(@str,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''), '8',''),'9',''),'/',''),' ','+'))) --replace space with a + to avoid empty string
PRINT ''
GO
DECLARE @str varchar(10)
SET @str = '12/ /2012'
IF convert(int, substring(@str,4,2)) <= 31 AND convert(int, substring(@str,4,2)) >= 1
PRINT @str+': Passed Test'
ELSE PRINT @str+': Failed Test'
GO
DECLARE @str varchar(10)
SET @str = '12/ /2012'
PRINT 'Number of characters in ' + @str + ' that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): ' + convert(varchar(5),len(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(@str,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''), '8',''),'9',''),'/',''),' ','+'))) --replace space with a + to avoid empty string
Output:
--Output
--12/10/2012: Passed Test
--Number of characters in 12/10/2012 that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): 0
--Msg 245, Level 16, State 1, Line 4
--Conversion failed when converting the varchar value '!0' to data type int.
--Number of characters in 12/!0/2012 that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): 1
--12/ /2012: Failed Test
--Number of characters in 12/ /2012 that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): 2
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?
asked Mar 28, 2011 at 23:10
1
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
answered Mar 28, 2011 at 23:14
![]()
Martin SmithMartin Smith
429k87 gold badges725 silver badges824 bronze badges
12
But if i take the piece of sql and run it from sql management studio, it will run without issue.
If you are at liberty to, change the service account to your own login, which would inherit your language/regional perferences.
The real crux of the issue is:
I use the following to convert -> date.Value.ToString(«MM/dd/yyyy HH:mm:ss»)
Please start using parameterized queries so that you won’t encounter these issues in the future. It is also more robust, predictable and best practice.
answered Mar 28, 2011 at 23:35
RichardTheKiwiRichardTheKiwi
105k26 gold badges196 silver badges262 bronze badges
4
I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.
You better execute set datetime <format> (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don’t get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with ‘yyyy-MM-dd HH:mm:ss:ffff’ formats.
To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').
For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)
answered Jul 4, 2013 at 14:29
![]()
Iván SainzIván Sainz
3695 silver badges12 bronze badges
It’s a date format issue. In Ireland the standard date format for the 28th of March would be «28-03-2011», whereas «03/28/2011» is the standard for the USA (among many others).
answered Mar 28, 2011 at 23:16
srgergsrgerg
18.4k4 gold badges55 silver badges39 bronze badges
I know that this solution is a little different from the OP’s case, but as you may have been redirected here from searching on google the title of this question, as I did, maybe you’re facing the same problem I had.
Sometimes you get this error because your date time is not valid, i.e. your date (in string format) points to a day which exceeds the number of days of that month!
e.g.: CONVERT(Datetime, '2015-06-31') caused me this error, while I was converting a statement from MySql (which didn’t argue! and makes the error really harder to catch) to SQL Server.
answered Aug 31, 2016 at 23:29
![]()
Mohsen KamraniMohsen Kamrani
7,0495 gold badges40 silver badges64 bronze badges
You could use next function to initialize your DateTime variable:
DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
answered Oct 27, 2021 at 12:42
![]()
1
JAVA8: Use LocalDateTime.now().toString()
answered May 28, 2018 at 10:52
ariabeleariabele
3551 gold badge4 silver badges9 bronze badges
i faced this issue where i was using SQL it is different from MYSQL
the solution was puting in this format:
=date(‘m-d-y h:m:s’);
rather than
=date(‘y-m-d h:m:s’);
answered Sep 26, 2019 at 10:09
![]()
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?
asked Mar 28, 2011 at 23:10
1
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
answered Mar 28, 2011 at 23:14
![]()
Martin SmithMartin Smith
429k87 gold badges725 silver badges824 bronze badges
12
But if i take the piece of sql and run it from sql management studio, it will run without issue.
If you are at liberty to, change the service account to your own login, which would inherit your language/regional perferences.
The real crux of the issue is:
I use the following to convert -> date.Value.ToString(«MM/dd/yyyy HH:mm:ss»)
Please start using parameterized queries so that you won’t encounter these issues in the future. It is also more robust, predictable and best practice.
answered Mar 28, 2011 at 23:35
RichardTheKiwiRichardTheKiwi
105k26 gold badges196 silver badges262 bronze badges
4
I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.
You better execute set datetime <format> (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don’t get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with ‘yyyy-MM-dd HH:mm:ss:ffff’ formats.
To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').
For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)
answered Jul 4, 2013 at 14:29
![]()
Iván SainzIván Sainz
3695 silver badges12 bronze badges
It’s a date format issue. In Ireland the standard date format for the 28th of March would be «28-03-2011», whereas «03/28/2011» is the standard for the USA (among many others).
answered Mar 28, 2011 at 23:16
srgergsrgerg
18.4k4 gold badges55 silver badges39 bronze badges
I know that this solution is a little different from the OP’s case, but as you may have been redirected here from searching on google the title of this question, as I did, maybe you’re facing the same problem I had.
Sometimes you get this error because your date time is not valid, i.e. your date (in string format) points to a day which exceeds the number of days of that month!
e.g.: CONVERT(Datetime, '2015-06-31') caused me this error, while I was converting a statement from MySql (which didn’t argue! and makes the error really harder to catch) to SQL Server.
answered Aug 31, 2016 at 23:29
![]()
Mohsen KamraniMohsen Kamrani
7,0495 gold badges40 silver badges64 bronze badges
You could use next function to initialize your DateTime variable:
DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
answered Oct 27, 2021 at 12:42
![]()
1
JAVA8: Use LocalDateTime.now().toString()
answered May 28, 2018 at 10:52
ariabeleariabele
3551 gold badge4 silver badges9 bronze badges
i faced this issue where i was using SQL it is different from MYSQL
the solution was puting in this format:
=date(‘m-d-y h:m:s’);
rather than
=date(‘y-m-d h:m:s’);
answered Sep 26, 2019 at 10:09
![]()
- Remove From My Forums
-
Question
-
Hello, Using SQL 2008 R2.
I read several answers, but did not see an answer that worked for my situation.
I am importing flat files from various places which have different date formats, and I want to do cleanup of the date formats.
Here is the command I am using:
UPDATE SalesTempTest set out_date = Convert(nvarchar(20),Cast(out_date as datetime),101) Where ISDATE(out_date) = 1;
This works, but occationally gets the error ‘conversion of a varchar data type to a datetime data type resulted in an out-of-range value’.
Thank you for any recommendations.
Tom
MisterT99
-
Edited by
Friday, April 5, 2013 11:04 PM
-
Edited by
Answers
-
Wow, so many answers on such a basic question, and no one can give the correct answer!
What is going on is that the optimizer may decide evaluate expressions earlier for better performance, but at the risk that things go wrong. I don’t like it, but Microsoft don’t seem to give in. And similar issues exists in other engines.
Anyway, the only guarantee to avoid that this does not happen is to use CASE:
UPDATE SalesTempTest
set out_date = CASE WHEN isdate(out_date) = 1
THEN Convert(nvarchar(20),
Cast(out_date as datetime),101)
END
Where ISDATE(out_date) = 1;Of course, using (n)varchar for datetime values is a bad idea, but if you get data on flat files, bad dates are part of the game.
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
-
Marked as answer by
Mister T99
Saturday, April 6, 2013 1:56 PM
-
Marked as answer by
|
3 / 3 / 0 Регистрация: 25.12.2013 Сообщений: 7 |
|
|
1 |
|
|
03.06.2017, 15:57. Показов 57646. Ответов 13
Проблема:При открытии базы данных mssql происходит ошибка :Преобразование типа данных nvarchar в тип данных datetime привело к выходу значения за пределы диапазона.
__________________
1 |
|
1039 / 855 / 335 Регистрация: 08.12.2016 Сообщений: 3,283 |
|
|
03.06.2017, 16:18 |
2 |
|
ну показали бы хоть строку скрипта, на которой ошибка происходит
0 |
|
1107 / 753 / 181 Регистрация: 27.11.2009 Сообщений: 2,241 |
|
|
03.06.2017, 16:32 |
3 |
|
ну показали бы хоть строку скрипта, на которой ошибка происходит И строку, содержащую дату, которая не конвертируется.
0 |
|
lowwro 3 / 3 / 0 Регистрация: 25.12.2013 Сообщений: 7 |
||||
|
03.06.2017, 19:30 [ТС] |
4 |
|||
|
ну показали бы хоть строку скрипта, на которой ошибка происходит
И это не одна строчка,их много,но везде где есть дата,вот такая вот ошибка.
0 |
|
invm 3317 / 2027 / 722 Регистрация: 02.06.2013 Сообщений: 4,972 |
||||||||||||
|
03.06.2017, 22:10 |
5 |
|||||||||||
|
Вместо
написать
или
1 |
|
1039 / 855 / 335 Регистрация: 08.12.2016 Сообщений: 3,283 |
|
|
03.06.2017, 22:40 |
6 |
|
Начиная с версии SQL Server 2012, единственные стили, которые поддерживаются при преобразовании из даты и времени с типами datetimeoffset 0 или 1. Все другие стили преобразования возвращают ошибку 9809. на 2005 первоначальная конвертация (как у ТС) работает без ошибок. Похоже, что в колледже версия сервера ниже 2012, а дома — нет
1 |
|
3 / 3 / 0 Регистрация: 25.12.2013 Сообщений: 7 |
|
|
04.06.2017, 02:56 [ТС] |
7 |
|
У меня около 100 строчек этого кода( Добавлено через 1 минуту Добавлено через 1 минуту
Вместо
Вместо у меня около 100 строчек таких(
0 |
|
1039 / 855 / 335 Регистрация: 08.12.2016 Сообщений: 3,283 |
|
|
04.06.2017, 02:59 |
8 |
|
тогда сервер поставьте ниже 2012-го Добавлено через 2 минуты
0 |
|
invm 3317 / 2027 / 722 Регистрация: 02.06.2013 Сообщений: 4,972 |
||||
|
04.06.2017, 12:33 |
9 |
|||
|
Решение
У меня около 100 строчек этого кода( Ну если так лень исправлять, добавьте в начало скрипта
5 |
|
3 / 3 / 0 Регистрация: 25.12.2013 Сообщений: 7 |
|
|
04.06.2017, 14:16 [ТС] |
10 |
|
Ну если так лень исправлять, добавьте в начало скрипта Оказывается такое легкое решение,спасибо тебе)Реально,вот большое спасибо!
2 |
|
papaflash 0 / 0 / 0 Регистрация: 09.04.2020 Сообщений: 3 |
||||||||
|
03.09.2021, 12:04 |
11 |
|||||||
|
Я конечно запоздал с ответом, возможно новичкам пригодится. В поиске Яндекса данная тема вторая по списку.
Можно добавить в начало скрипта:
0 |
|
marina2 Рожденная для битвы 285 / 64 / 12 Регистрация: 08.11.2009 Сообщений: 1,226 |
||||
|
25.08.2022, 14:20 |
12 |
|||
|
А как нормально присвоить столбцу значение даты?
Аналогичная ошибка.
0 |
|
Andrey-MSK 1324 / 842 / 198 Регистрация: 14.08.2018 Сообщений: 2,746 Записей в блоге: 3 |
||||
|
25.08.2022, 17:40 |
13 |
|||
|
А как нормально присвоить столбцу значение даты?
0 |
|
PaulWist 249 / 149 / 77 Регистрация: 12.04.2022 Сообщений: 612 |
||||
|
26.08.2022, 10:48 |
14 |
|||
|
— Если сервер не на русской локали
0 |
- Remove From My Forums
-
Вопрос
-
Hi everyone,
I am getting the error «The conversion of a varchar data type to a datetime data type resulted in an out-of-range value» when I try to pull some data from my shift plan table.
The piece of code causing the error is
case when [Start] = '' then '' else cast(substring(left(replace([Start],'/','-'),10),7,10)+'-'+substring(left(replace([Start],'/','-'),10),4,2)+'-'+substring(left(replace([Start],'/','-'),10),1,2) + ' ' + cast(cast(convert(datetime, right([start],11), 131)as time) as char(8)) as datetime) end as [Start]
The [Start Date] column in the table looks like this
Any help is much appreciated.
Thanks
Ответы
-
You are doing
cast(convert(datetime, right([start],11), 131)as time)
which gets the last 11 characters and tries to convert the value to a datetime. You need the characters beginning with the 11th character which would be
cast(convert(datetime, substring([start],11,len([start])), 131)as time)
Tom
-
Помечено в качестве ответа
18 июля 2019 г. 4:15
-
Помечено в качестве ответа
-
Then you will need to put those years of tsql experience to work to write your own conversion and validation logic. If you want help, you need to explain what range of values exist and the logic you propose to convert.
You should know by now that CASE is an expression that returns a single value of a specific datatype. Your first branch returns an empty string but your second branch returns a datetime. That empty string will be implicitly converted to datetime resulting
in a value that you probably do not want to see. In addition, you can convert the single value you included in your sample data directly to datetime without the need for your logic (using standard US regional settings).I put some sample data into
dbfiddle to demonstrate converting in different ways — and to demonstrate some of the problems with your logic. As already mentioned your logic to isolate the time was incorrect. Your logic to isolate the date was also overly complicated — but at least
did not produce an error. Of course, all this assumes you have valid dates and times stored in a consistent pattern. You need to verify that assumption.-
Помечено в качестве ответа
lrj1985
18 июля 2019 г. 4:15
-
Помечено в качестве ответа
-
Hi lrj1985,
scott_morris-ga already provided a full answer above.
Just in case, if you like string manipulations, please try the following:
DECLARE @tbl TABLE ( ID INT IDENTITY(1, 1) PRIMARY KEY, Start VARCHAR(30) ); INSERT INTO @tbl(Start) VALUES ('07/17/2019 6:00 PM');
-- Date and time format - ISO 8601 SELECT * , CAST(SUBSTRING([Start],7, 4) + '-' + SUBSTRING([Start], 1, 2) + '-' + SUBSTRING([Start], 4, 2) + 'T' + CAST(CAST(CONVERT(DATETIME, substring([Start], 11,len([start])), 131) AS TIME) AS CHAR(8))AS DATETIME) AS RealDateTime FROM @tbl;
Output:
ID Start RealDateTime 1 07/17/2019 6:00 PM 2019-07-17 18:00:00.000
-
Изменено
Yitzhak Khabinsky
18 июля 2019 г. 4:08 -
Помечено в качестве ответа
lrj1985
18 июля 2019 г. 4:15
-
Изменено

Сообщение было отмечено lowwro как решение