Error in when comparing British format date in where clause - sql

When I run this in sql server2005 I got error.
select * from productratedates
where RateDate BETWEEN '31/10/2009' AND '03/11/2009'
Error: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
But When I run this in SQl server 2005. It is perfectly all right.
select * from productratedates
where RateDate BETWEEN '2009-10-31' AND '2009-11-03'
I want to compare date in British format.
Any help!!

Your comment says you'd like to enter dates in the day/month/year format. You can choose that format using SET DATEFORMAT:
SET DATEFORMAT dmy;
For example:
set dateformat dmy
select cast('31/10/2009' as datetime) -- succeeds
set dateformat mdy
select cast('31/10/2009' as datetime) -- fails
You can retrieve the current dateformat setting with DBCC:
dbcc useroptions
A list of available languages, with their dateformat, is available from:
exec sp_helplanguage
For me, the language called "British" has dateformat dmy. So you can change the default language for your login to British (from the property page of your login.) You can even specify it in the connection string:
Server=<server>;Uid=<login>;Pwd=<password>;Current Language=British

You could convert the date to YYYY-MM-DD format before you send it to the server.

Dates get read in US format where possible, so '31/10/2009' has to be UK format, but '03/11/2009' flips over to 11th March. That messes up your BETWEEN by going backwards in time.
I don't know if it would work for you, but we always use the format dd-mmm-yyyy:
select * from productratedates where RateDate BETWEEN '31-oct-2009' AND '03-nov-2009'

How a date is formatted is actually an interface thing. If you are looking purely at the data dates should ALWAYS be in one specific format YYYY/MM/DD.
Your interface is responsible for displaying the date in the localized format. By using this practice the script is ambiguous about where it is used and what language it is. so comparing the date should always be done in the standardized format.
What I suggest you to do is have your interface show it in the format you like and the back-end (including SQL statements) to be the standardized date format.

Related

Database export fails when I try to export this format '2020-04-13 14:13:54'

When I try to execute this insert
INSERT INTO BCS_EXPEDIENTES_REGISTRADOS (FOLIO, DOCUMENTO, FECHA_REGISTRO_DPS, CANT_PAGINAS)
VALUES ('24', 'Suc4437_X722INSURGEN_20200305033042.tiff', '2020-04-13 14:13:54', '79')
I get an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The process is:
I have a value example: 04/13/2020 09:13:41
I convert this value to this format: =format([G_RECEPCION], "yyyy-MM-dd HH:mm:ss") to 2020-04-13 14:13:54
But when I execute the INSERT, it throws that error.
Any ideas for this case? I need to export the datetime in this format on SQL Server yyyy-MM-dd HH:mm:ss
Let me start by saying that datetime has no concept of display format.
The display format is only relevant when we talk about the string representations of datetime values.
Then, lets take a look at the format you're using: yyyy-MM-dd HH:mm:ss (known as ODBC canonical).
When converting strings of this format to DateTime, the result of the conversion is culture dependent.
This means that when operating in some languages (like English) SQL Server will attempt to use yyyy-MM-dd as date, but in other languages (like German) it will attempt to use yyyy-dd-MM as date.
This is the the reason you get a conversion error.
Importent note: Unless you explicitly set the language (or DateFormat, for that matter), SQL Server will use the default language of the login - so for some users conversion might fail while for other users it will succeed.
Another note is that this problem only exists with DateTime, but not with DateTime2 - converting this format to DateTime2 will always be interpreted as yyyy-MM-dd.
So, considering all this information, you have three options here:
Stop using DateTime, use DateTime2 instead.
Instead of using the unsafe ODBC canonical format use the safe ISO8601 format whenever dealing with string representation of datetime values: yyyy-mm-ddThh:mi:ss.mmm.
Explicitly set language or date format (to ymd) before your insert statement.
I would recommend combining the first two and avoid using the third if possible.
DateTime2 is a better data type than DateTime, and ISO 8601 is the universal standard and is supported throughout different platforms and languages as an unambiguous datetime format.

How do I change the date in SQL Server 2017 to UK format?

I have got several tables in my database (with data) that is formatted in the American standard of mm/dd/yyyy. Is there a way to convert the date to a British format (i.e. dd/mm/yyyy) that doesn't involve dropping and recreating the tables?
Thanks!
I set my data type to >date when I was creating my table. I can store dates in the format mm/dd/yyyy, but not dd/mm/yyyy.
As I've mentioned in my comment, dates are not stored with their display format - in fact, you can say that dates have no display format - only string representation of dates have a display format.
Whenever dealing with string literals representing date and datetime values in SQL server, use ISO 8601 datetime format (yyyy-MM-ddTHH:mm:ss or yyyyMMddTHHmmss).
SQL Server guarantees to properly parse this string representation into date / datetime values, without ambiguity.
Please note the T seperator between the date and the time. There is a very similar standard format, where the T is replaced with a white-space, but the DateTime data type have a bug parsing this format - and it is culture-dependent (Note that DateTime2 does not have that bug) - and that's another reason why you should never use datetime again.
When you use a string literal like '25/03/2018' it's easy for a human to see that it stands for March 25th 2018, but SQL Server will raise an error trying to parse this string into a date if the current value of DATEFORMAT is not DMY.
However, SQL Server will always parse ISO 8601 string representation of dates correctly, regardless of any local settings or previous set dateformat or set language statements etc'. '2018-02-01T15:40:50' will always be parsed is February 1st 2018, 3:40:50 PM.
Unless specified, As Martin Smith wrote in his comment, the default dateformat depends on the defualt language settings of the current login - so a query that works for one login might raise an error for another login - and that's another good reason never to trust culture-specific string representation of datetime.
DECLARE #dt DATETIME = '01/20/2019';
SELECT FORMAT( #dt, 'd', 'en-gb' ) AS 'UK'
Are you referring to the date format displayed by SQL Server Management Studio or a similar application? The format is controlled by Windows Control Panel settings, not by SQL Server. There is no internal format for dates in SQL Server.
This is defined by default from the machine where is running MS SQL Server.
To see all available cultures please do:
select * from sys.syslanguages
Then, you can change SQL Server language using:
SET LANGUAGE BRITISH
... and the date format will always be like you want.
Note: this will change all the database (not just the date format), the other way is to change the date format using the FORMAT function in T-SQL.

DATETIME format set to YYYY:MM:DD in SQL but insert query runs on DD:MM:YYYY in SQL Developer

I have DATETIME set as
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); in my getDateTime() method in my DTO class and this method returns a date with time. This is further used to create a CSV(Excel) file but when I run INSERT/UPDATE query in SQL developer, it throws an error if I use the format as YYYY:MM:DD HH:MM'. ForDD:MM:YYYY HH:MMit runs successfully. Also in some cases while creating CSV, the date field gets missed. I have also checked DB table and the format for DATE is set as DATE in there. Can anyone suggest the possible reason for
Error in SQL Dev while Updating/Inserting date as yyyy-MM-dd HH:mm
What the DATE field's format should be in SQL if my code has format as above. Or DATE should work just fine.
We are using Oracle as RDBMS. For running queries we use SQL Developer.
Take a look in your Tools => Preferences => Databases => NLS section in SQL Developer. It nominates the default date format (amongst other things) that the tool will expect. You can alter this to suit your needs.
There are a lot of misconceptions in the question:
I have DATETIME
Oracle does not have a DATETIME data type - it has DATE or TIMESTAMP both of which have a time component.
set as DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
A DATE (or TIMESTAMP) column does not have a format; Oracle stores DATE data types as 7-bytes (and similar for TIMESTAMP data types) and it is not until it is passed to a client program (i.e. SQL/Plus, SQL Developer, Toad, Java, Python, etc) and that client program formats it according to whatever rules it has that the date gets a format.
The default string format for dates in SQL/Plus or SQL Developer is set by the NLS_DATE_FORMAT session parameter. Other clients will typically have parameters that you can set for the default date format (if they don't also use the NLS settings). However, beware that the NLS_DATE_FORMAT is a session parameter so it belongs to the user's session and multiple users can each have a different value for the parameter corresponding to how they have set it.
If you have overridden the default date format settings in the SQL Developer IDE then you can change it in "Tools" > "Preferences" > "Database" > "NLS".
For DD:MM:YYYY HH:MM it runs successfully.
The format model MM (and mm as it is not case sensitive) is for month and HH is a 12-hour clock so you are specifying:
day:month:year hours-on-12-hour-clock:month
If you want to give a date a specific format then you will need to convert it to a string:
SELECT TO_CHAR( SYSDATE, 'MM/DD/YYYY HH24:MI' )
FROM DUAL;
or if you want to convert a string to a date then use:
SELECT TO_DATE( your_string, 'MM/DD/YYYY HH24:MI' )
FROM DUAL;
Also in some cases while creating CSV, the date field gets missed.
It probably is not missed - it is probably just NULL and gets formatted as an empty string.

SQL WHERE DateTime is Between

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.

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)