I have faced the same problem a week ago. The problem is with the time zone setting. Specify in other formats like mm/dd/yyyy (usually works).

Specifying the date as 30/12/2013 resulted in the error for me. However, specifying it as mm/dd/yyyy format worked.

If you need to convert your input the you can try looking into the CONVERT method. Syntax is

CONVERT(VARCHAR,@your_date_Value,103)

CONVERT(VARCHAR, '12/30/2013', 103)

The finishing 103 is the datetime format.

Refer this link for conversion formats and further reading. https://www.w3schools.com/sql/func_sqlserver_convert.asp

Answer from Mahe on Stack Overflow
🌐
BoldBI
support.boldbi.com › kb › article › 13055 › resolving-sql-server-exception-conversion-of-varchar-data-type-to-datetime-data-type-resulted-in-an-out-of-range-value
Resolving SQL Server Exception: Conversion of Varchar Data Type to Datetime Data Type Resulted in an Out-of-Range Value
October 16, 2023 - Reason: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.” This error typically occurs when there is a mismatch in the date format.
Discussions

Error when conversion of a varchar data type to a datetime
Hi, I have column NMDT decimal(8,0) - In one table Last_Date datetime2(7) - In another table wants to convert NMDT (decimal) column as Last_Date (Datetime2). I write below query but getting error message. CASE WHEN NMDT = 0 THEN NULL ELSE… More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
December 7, 2023
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value. UWP
Hey Everyone Have been having this issue trying to insert a new object into the DB. For some reason it works fine under mobile devices, however when its being used with UWP, it seems to throw this error. I have a class 'SalesOrder' which has Id… More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
January 4, 2023
Varchar to date
Hi, I am converting the varchar value to date. the date values are stored in the SQL table in the format of DD/MM/YYYY. below query was tried to convert varchar to date : CONVERT(date, dt, 103) Error : Msg 241, Level 16, State 1,… More on learn.microsoft.com
🌐 learn.microsoft.com
2
0
Out of range data conversion error
This browser is no longer supported · Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support More on learn.microsoft.com
🌐 learn.microsoft.com
2
0
December 16, 2014
Top answer
1 of 1
4

As pointed out by Martin Smith in his deleted answer:

It is the default language of the login that determines the default way that string dates are interpreted but this is not relevant to your question as you are specifying the style parameter explicitly anyway.

Possible Solutions

Nonetheless, I would like to point out a couple of possible solutions.

WARNING
Please read before applying any of the given solution.
Both solution could cause issues in production. Backup your database / data beforehand.

1. Change SQL Server Instance Language

Set the default language of the SQL Server instance via:

EXEC sys.sp_configure N'default language', N'23'
GO
RECONFIGURE WITH OVERRIDE
GO

23 is the langid for British English as can be retrieve in the sys.syslanguages table:

+--------+------------+-----------+---------+---------+-----------------+---------------------------------------------------------------------------------------+-------------------------------------------------+----------------------------------------------------------+------+-----------+
| langid | dateformat | datefirst | upgrade |  name   |      alias      |                                        months                                         |                   shortmonths                   |                           days                           | lcid | msglangid |
+--------+------------+-----------+---------+---------+-----------------+---------------------------------------------------------------------------------------+-------------------------------------------------+----------------------------------------------------------+------+-----------+
|     23 | dmy        |         1 |       0 | British | British English | January,February,March,April,May,June,July,August,September,October,November,December | Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec | Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday | 2057 |      1033 |
+--------+------------+-----------+---------+---------+-----------------+---------------------------------------------------------------------------------------+-------------------------------------------------+----------------------------------------------------------+------+-----------+

NOTE / CAUTION!
However, I would not recommend this as your SQL Server instance "has been"/"is" running with a predefined language. You might break things. Please test before implementing!

You can verify the server's current running settings with this script:

SELECT sc.value_in_use, sl.langid, sl.name, sl.alias,sl.[dateformat] FROM sys.configurations AS sc 
    JOIN sys.syslanguages AS sl
        ON sl.langid = sc.value_in_use 
WHERE sc.name = 'default language';

On my SQL Server instance this yields:

+--------------+--------+------------+---------+------------+
| value_in_use | langid |    name    |  alias  | dateformat |
+--------------+--------+------------+---------+------------+
|            0 |      0 | us_english | English | mdy        |
+--------------+--------+------------+---------+------------+

2. Change Client Connection Settings

Change the language setting in the script you are currently running with the following SET command:

set language = uk_english
go
<your statements>
go

NOTE / CAUTION
Please test before using in production.

3. Set Dateformat

Change the dateformat before you run your script:

set dateformat MDY
go
<your statements>
go

4. Change the Default Language of the SQL Server Login

In case you want to change the default language of the SQL Server login execute a similar script to:

USE [master]
GO
ALTER LOGIN [mojo] WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[British], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO

Reference Reading

  • sys.syslanguages (Transact-SQL)
  • SET LANGUAGE (Transact-SQL)
  • Configure the default language Server Configuration Option
  • Server Configuration Options (SQL Server)
  • SET DATEFORMAT (Transact-SQL)
  • ALTER LOGIN (Transact-SQL)
  • International Settings (Windows 11)
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 624866 › the-conversion-of-a-nvarchar-data-type-to-a-dateti
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value. UWP - Microsoft Q&A
January 4, 2023 - One solution is to use explicit conversion for the date field in the query · e.g. INSERT INTO <YourTable> (<your columns list>) VALUES (....., CONVERT(DATETIME, @datetimeParam, 103), ......)
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 850079 › out-of-range-data-conversion-error
Out of range data conversion error - Microsoft Q&A
December 16, 2014 - declare @month int=null Set @month=12 select * from Table_A where CAST(CONVERT(datetime, TableLocalDate, 131) AS DATE) <=DATEADD(MONTH,@Month*-1, GETDATE()) "The conversion of a varchar data type to a date time data type resulted in an out-of-range ...
🌐
SQLTeam
forums.sqlteam.com › transact-sql
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value - Transact-SQL - SQLTeam.com Forums
May 14, 2015 - Hi all, hope in your help. I have problem to execute query with interval date. If try this query I don't have problem and the output is correct: SELECT * FROM dotable WHERE dotableDate BETWEEN CONVERT (datetime, '01/01/2015', 121) AND CONVERT (datetime, '09/01/2015', 121); Instead if try this I have error: SELECT * FROM dotable WHERE dotableDate BETWEEN CONVERT (datetime, '25/01/2015', 121) AND CONVERT (datetime, '28/01/2015', 121); [Err] 22007 - [SQL Server]The conversion of a varchar ...
Find elsewhere
Top answer
1 of 5
10

I checked your profile and saw that you are in the UK. If your sql server is set to use the dateformat dmy then that explains your issue. Without using the 'T' instead of the space in the datetime string, Sql Server won't recognize it as ISO8601 format.

Try this:

select count(*) 
  from dbo.profile 
  where [created] between convert(datetime,'2014-11-01T00:00:00.000') 
                      and convert(datetime,'2014-11-30T23:59:59.997');

Querying using dates and/or datetimes can be tricky, to make sure you are getting what you are looking for I recommend reading:

  • Aaron Bertrand's Bad habits to kick : mis-handling date / range queries
  • Robyn Page's SQL Server DATE/TIME Workbench

edit: to clarify the out of range value in your error message would be from interpreting the month as 30 and the day as 11.

2 of 5
8

I do not understand why the data is being converted from varchar to datetime when 'Created' is set to datetime

The literals you are providing for comparison to the Created column are strings. To compare those literals with the datetime column, SQL Server attempts to convert the strings to datetime types, according to the rules of data type precedence. Without explicit information about the format of the strings, SQL Server follows its convoluted rules for interpreting strings as datetimes.

In my view, the neatest way to avoid these types of issues is to be explicit about types. SQL Server provides the CAST and CONVERT functions for this purpose. When working with strings and date/time types, CONVERT is to be preferred because it provides a style parameter to explicitly define the string format.

The question uses strings in ODBC canonical (with milliseconds) format (style 121). Being explicit about the data type and string style results in the following:

SELECT COUNT(*)
FROM dbo.profile 
WHERE [Created] BETWEEN 
    CONVERT(datetime, '2014-11-01 00:00:00.000', 121)
    AND 
    CONVERT(datetime, '2014-11-30 23:59:59.997', 121);

That said, there are good reasons (as Aaron points out in his answer) to use a half-open range instead of BETWEEN (I use style 120 below just for variety):

SELECT COUNT(*)
FROM dbo.profile 
WHERE
    [Created] >= CONVERT(datetime, '2014-11-01 00:00:00', 120)
    AND [Created] < CONVERT(datetime, '2014-12-01 00:00:00', 120);

Being explicit about types is a very good habit to get into, particularly when dealing with dates and times.

🌐
SQLServerCentral
sqlservercentral.com › forums › topic › conversion-of-a-varchar-data-type-to-a-datetime-data-type-resulted-in-an-out-of-range-value
conversion of a varchar data type to a datetime data type resulted in an out-of-range value – SQLServerCentral Forums
April 23, 2020 - The datatype of this column in table is datetime, right? if not then there might be some values which might not get convered to dateime datatype. I picked some values, and they seem to be working fine.
🌐
Inductive Automation
forum.inductiveautomation.com › ignition
Converting a varchar data type to a datetime data type created an out of range value - Ignition - Inductive Automation Forum
March 18, 2016 - I am positive that this issue is related to SQL but still wanted to see if someone experienced something similar. I am writing very simple queries dynamically from a template. For example : But when it executes it throws following error: Sorry its in French which translates to : UPDATE lab_test_compound_specification SET date_edited = '2020-04-22 19: 31: 48.930', maximum = 1.55 WHERE id = 4 SQL error for "UPDATE lab_test_compound_specification SET date_edited = '2020-04-22 19: 31: 48.9...
🌐
GitHub
github.com › dotnet › efcore › issues › 29893
FirstOrDefault on DateTime column projection throws SqlException "The conversion of a varchar data type to a datetime data type resulted in an out-of-range valued" when sequence contains 0 items · Issue #29893 · dotnet/efcore
July 17, 2017 - FirstOrDefault on DateTime column projection throws SqlException "The conversion of a varchar data type to a datetime data type resulted in an out-of-range valued" when sequence contains 0 items#29893
Author   janseris
Top answer
1 of 2
4
Simple: never concatenate strings to form an SQL command- it's very dangerous, as well as causing conversion problems such as this. Always use parameterized queries instead, and pass the DateTime value directly without conversion. Your code will no longer be print took SQL Injection attacks, and your problem will disappear the same time.
2 of 2
0
First of all, you need to check the value of DateTime.Now.Date.ToShortDateString(), you may get a surprise, sometimes. · The answer depend on computer culture settings. · Use the debugger to see the value as the program runs. · ----- · You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect. · The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.Debugger - Wikipedia, the free encyclopedia[^]Mastering Debugging in Visual Studio 2010 - A Beginner's Guide · The debugger is here to show you what your code is doing and your task is to compare with what it should do. · There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug. · Quote: · Select * from table where [Date]=CONVERT(VARCHAR,'" + DateTime.Now.Date.ToShortDateString() + "',111)" · Never do this, because it promote a user input to SQL command and can lead to a problem called SQL Injection.SQL injection - Wikipedia[^]SQL Injection The solution to SQL injection will also solve your problem as sql server will know that your date is a date.
🌐
Infotopics
support.appsfortableau.infotopics.com › help center › documentation › writebackextreme
SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value writebackextreme databasedriver odbc
🌐
Rssing
sqlserverlearner7.rssing.com › chan-21678817 › article22.html
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
May 25, 2019 - When you try to convert varchar datatype to datetime you would get this error when the value in varchar datatype does not represent the correct range of date. ... 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.
🌐
FoxLearn
foxlearn.com › sql › fix-the-conversion-of-a-varchar-data-type-to-a-datetime-data-type-resulted-in-an-out-of-range-value-3844.html
How to fix 'The conversion of a varchar data type to a datetime data type resulted in an out-of-range value'
The error you're encountering, ... value," typically occurs when trying to convert a string that doesn't match the expected datetime format for your SQL server's locale or when the string represents an invalid date...
🌐
SQLTeam
forums.sqlteam.com › sql server administration
The conversion of a date data type to a smalldatetime data type resulted in an out-of-range value - SQL Server Administration - SQLTeam.com Forums
April 25, 2012 - hi experts, The view being selected from contains 1 date column which is defined as smalldatetime. Selecting from the view view results in this error: The conversion of a date data type to a smalldatetime data type resulted in an out-of-range value. I ran select MyDateColumn from MyView where ...