SQL WHERE DateTime is Between - sql

I have this query here:
SELECT *
FROM QuestionnaireAnswer
WHERE dateCreated BETWEEN CAST('20/12/2015' AS datetime) AND CAST('22/12/2015' AS datetime)
but I keep getting this error, how come? and how do I fix it?
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) 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:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer. In your concrete case, use this WHERE clause:
WHERE dateCreated BETWEEN '20151220' AND '20151222'
and you don't even need any explicit CAST operations (or if you want to use an explicit CAST - then I'd suggest you cast to a DATE datatype - rather than DATETIME).
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format 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 YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible

As a general rule when comparing dates in SQL Server don't use a format specific to a locale, use the universal ISO 8601 format 'yyyy/MM/dd' so the query becomes:
SELECT *
FROM QuestionnaireAnswer
WHERE dateCreated BETWEEN CAST('2015/12/20' AS datetime) AND CAST('2015/12/22' AS datetime)
You could also use one that is specific to a locale but you would have to ensure that the date format on the server always remains the same across all servers your code will connect to.

Using CONVERT you can write something like that:
SELECT *
FROM QuestionnaireAnswer
WHERE
dateCreated BETWEEN CONVERT(datetime, '20/12/2015', 103)
AND CONVERT(datetime, '22/12/2015', 103);

Check the locale settings on your server. My bet is that you are set for a US date format, but the date you have there is not in a US format.
More on querying the locale settings here.
This SO question has numerous ways to adjust the locale settings for SQL, including by user.
If you don't have permissions to change the locale for the whole server, you can change your locale within a session here. Note that SET LANGUAGE automatically sets the DATEFORMAT , but you can set the DATEFORMAT by itself.
To test this, try reversing the date and month in your date. Like so:
SELECT *
FROM QuestionnaireAnswer
WHERE dateCreated BETWEEN CAST('12/20/2015' AS datetime) AND CAST('12/22/2015' AS datetime)
Or try putting the date in a "locale insensitive format" like yyyymmdd HH:mm:ss.fff .

If column is a date field then you should do this:
SELECT *
FROM QuestionnaireAnswer
WHERE dateCreated BETWEEN TO_DATE('20-DEC-2015') AND TO_DATE('22-DEC-2015')
May not be 100% accurate depending on architecture and configuration.

Related

How to change date format of datetime data type in SQL?

My date format of "03-01-2017 10:24:48" is getting stored in SQL as "2017-03-01 10:24:48.000" where my 'dd-mm-yyyy' format is getting converted to 'yyyy-mm-dd' format.
How can I change the date format of the column to my desired format? My table already contains data.
SQL Server doesn't store a DateTime in any string format - it's stored as an 8 byte numerical (binary) value.
The various settings (language, date format) only influence how the DateTime is shown to you in SQL Server Management Studio - or how it is parsed when you attempt to convert a string to a DateTime.
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) 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:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format 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 YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible
Changing the format does not change the way the data is stored, just the way it is displayed. You can find date and time styles at https://msdn.microsoft.com/en-us/library/ms187928.aspx?f=255&MSPPError=-2147217396.

SQL Server : error conversion of a varchar data type

I'm trying to run a SQL query however I'm getting an error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Code:
SELECT
ClientId,
DatePassed,
Lender
FROM
dbo.tbl_Profile_Mortgage
WHERE
DatePassed = '2011-04-28 00:00:00.000'
I have converted the data type as so
SELECT
ClientId,
Convert (Date, DatePassed)
Lender
FROM
dbo.tbl_Profile_Mortgage
WHERE
DatePassed = '2011-04-28 00:00:00.000'
This however is still giving me the same error
Column DatePassed is of type datetime null
Any suggestions would be appreciated
Conceptually, you think the where clause is performed before the convert(). But that is not necessarily how the query is run. The only SQL statement that guarantees order of execution is case (and then not all the time).
You can try this:
SELECT ClientId,
(case when isdate(DatePassed) = 1 then Convert (Date, DatePassed) end),
Lender
FROM dbo.tbl_Profile_Mortgage
WHERE DatePassed = '2011-04-28 00:00:00.000';
EDIT:
Given that DatePassed is already in a date time format, then your error is highly unusual. This is not a problem from the conversion of this column, because no varchar is involved.
The only thing I can think of is the constant. Perhaps you have a strange setting for default dates and it is trying to get the 4th day of the 28th month. If so, you can readily fix this by putting in an explicit conversion with a format:
SELECT ClientId,
Convert(Date, DatePassed),
Lender
FROM dbo.tbl_Profile_Mortgage
WHERE DatePassed = convert(date, '2011-04-28 00:00:00.000', 121);
Aaron Bertrand has a rather extended discussion of this issue in his blog. By the way, even though I recognize the problem that he mentions with the YYYY-MM-DD format, I still use that by default. I consider it a bug that Microsoft has chosen not to recognize this ISO standard format (but just because I think it is a bug doesn't necessarily convince anyone else).
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not. I guess in your case, you're using a language setting that just plain doesn't work with that string literal you're using.
The way to solve this is to use the (slightly adapted) 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:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format 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 YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible.
In your concrete case - use this string in your WHERE clause:
WHERE DatePassed = '2011-04-28T00:00:00.000';
(notice the literal T between the date and time portions)

Getting European Date Format SQL

I have a Database set up with a column for Datetime.
In my application a have a date selector.
The issue is that the Db uses American Date Format (MM/DD/YYYY) where as the app uses European Date Format (DD/MM/YYYY).
Is there a way to set up the column in the database to use European date format?
I don't want to have to convert through the code in the application.
SQL Server doesn't store a DateTime in any string format - it's stored as an 8 byte numerical value, and a DATETIME is a DATETIME is a DATETIME.
The various settings (language, date format) only influence how the DateTime is shown to you in SQL Server Management Studio - or how it is parsed when you attempt to convert a string to a DateTime.
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT.
So if you want to see your DateTime in US format, use
SELECT CONVERT(VARCHAR(30), YourDateTimeColumn, 101)
and if you need European (British/French/German) format, use
SELECT CONVERT(VARCHAR(30), YourDateTimeColumn, 103)
It's is a commonly accepted "Best Practice" to avoid using dates as string as much as possible - if ever possible, use the native SQL Server and .NET DATETIME datatype for sending back and forth dates (which is independent of any regional formatting). Try to convert the DATETIME to string only when you need to show it (preferably only in your UI - not in your database!)
Update: if you want to insert DateTime values, as I said, I would strongly recommend to use a proper datatype - and not fiddle around with specifically formatted strings.
If you must use strings, then by all means use the (slightly adapted) 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:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format 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 YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible
About "YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME":
Another option is the usage of the usual space as separator between data and time: YYYYMMDD HH:MM:SS or YYYYMMDD HH:MM:SS.SSS.
But then, again, dashes have to be omitted: as said for the long format, " note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!"
Please note that the time part needs the semi-colons!
Converting to DateTime2 is more tolerant, it works with and without dashes, even using European locales.
Dates don't have a "format" - date representations have a format. You should be passing the dates as dates instead of strings to your application, then converting to strings in whatever format is appropriate.
Since you don't say what platform your application is in the code may change, but here's a solution in C#:
DateTime dt = reader.GetDateTime(dateColumnIndex);
string s = dt.ToString("dd/MM/yyyy");

Getting an error saying the conversion of a varchar data type to datetime resulted in an out of range value

I have this sql statement
select ord_type,
case
when entered_dt between '2013-02-01' and '2013-02-31' then 1
end
from oehdrhst_sql
I keep getting this error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Whats wrong with it... I can't seem to find a solution
SELECT ord_type
, CASE WHEN entered_dt BETWEEN '20130201' AND '20130228' --<-- There are only 28 days in Feb
THEN 1 ELSE NULL END
FROM oehdrhst_sql
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) 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:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format 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 YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.

SQL server 2012: Cast a varchar (255) column to datetime results to an out-of-range value error

I am trying to read a column from tbl1 with type varchar(255) and load it to tbl2 as type datetime. See code below.
SELECT CAST(LTRIM(RTRIM(NLCompany)) AS varchar(20)) AS SRC_NLCompany,
CAST(LTRIM(RTRIM(AccountCode)) AS varchar(8)) AS SRC_AccountCode,
CAST(LTRIM(RTRIM(DocumentNumber)) AS numeric(10, 0)) AS SRC_DocumentNumber,
CAST(LTRIM(RTRIM(PaymentType)) AS varchar(1)) AS SRC_PaymentType,
CAST(LTRIM(RTRIM(PostingDaybkDate)) AS datetime) AS SRC_PostingDaybkDate
FROM TBL1
Error: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
There are many string formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what language / dateformat settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) 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:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format 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 YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible