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

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.

Related

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.

Change Datetime format in Microsoft Sql Server 2012

Hi i want to change the default datetime type in sql server. I have already table who has rows and i dont want to delete them. Now the datetime format that had rows is: 2015-11-16 09:04:06.000 and i want to change in 16.11.2015 09:04:06 and every new row that i insert i want to take this datetime format.
SQL Server does not store DATETIME values in the way you're thinking it does. The value that you see is simply what the DBMS is choosing to render the data as. If you wish to change the display of the DATETIME type, you can use the FORMAT() built-in function in SQL Server 2012 or later versions, but keep in mind this is converting it to a VARCHAR
You can get the format you desire via the following:
SELECT FORMAT(YourDateField, N'dd.MM.yyyy HH:mm:ss')
There is no such thing as format of the DATETIME data type, it has no format by nature, formatted is the text representation you can set when converting to VARCHAR or some visualization settings of the client / IDE.
If you, however, want to be able to insert dates using string representations that are alternatively formatted (i.e. control the way string input is parsed to datetime type) you can check SET DATEFORMAT - as explained in the remarks section this will not change the display representation of date fields / variables.
SQL serve provide wide range of date formatting function or way by using that user can change date format as per his requirement.
Some of are giver bellow.
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)

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");

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

Error in when comparing British format date in where clause

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.