How to convert XML string value to datetime in SQL Server - sql-server

I have below code which selects a date value from an XML string in SQL Server. The string value returns format in ddmmyy and I need to convert this to T-SQL datetime type before saving it to a table.
SELECT TOP 1
list.n.value('(DOB/#value)[1]', 'datetime') AS 'DOB'
FROM
#ResultXML.nodes('/Variables') AS list(n)
XML file:
<Variables>
<DOB>111290</DOB>
</Variables>

You might try it like this:
DECLARE #XML XML=
'<Variables>
<DOB>111290</DOB>
</Variables>';
SELECT CONVERT(DATETIME,STUFF(STUFF(#XML.value('(/Variables/DOB)[1]','varchar(max)'),3,0,'/'),6,0,'/'),3)
First you use two times STUFF to get 11/12/90 instead of 111290, than you use the 3 to convert this to datetime (or any other fitting format: use . for german, - for british...) More details on CAST and CONVERT
Best was, to store date and time values properly. Within XML this should be ISO8601, which means yyyy-MM-dd or yyyy-MM-ddThh:mm:ss More details on ISO8601

If SQL 2012+
The example
Declare #String varchar(25)= '111290'
-- If MMDDYY
Select DATEFROMPARTS(iif(Right(90,2)>25,'19'+Right(90,2),'20'+Right(90,2)),Left(#String,2),Substring(#String,3,2))
-- If DDMMYY
Select DATEFROMPARTS(iif(Right(90,2)>25,'19'+Right(90,2),'20'+Right(90,2)),Substring(#String,3,2),Left(#String,2))
Returns: 1990-11-12
Returns: 1990-12-11

Related

String with dd-MM-yyyy hh:mm:ss format to datetime in SQL Server

I'm trying to convert a nvarchar(max) column to a datetime in SQL Server. The format is dd-MM-yyyy hh:mm:ss, which I'd like to keep, however I'd like to change the type to datetime. I've found many similar questions about this conversion, but not with my particular format.
I've tried CONVERT(nvarchar(MAX), string_column, 121), however without luck. How can this be done? As example, I'd like to convert the string 26-11-2021 08:19:16 to datetime.
This works for me:
SELECT CONVERT(datetime2(0), '26-11-2021 08:19:16', 105);
/* Output: 2021-11-26 08:19:16 */
Recent versions of SQL Server also have the TRY_PARSE method:
SELECT TRY_PARSE('26-11-2021 08:19:16' As datetime2(0) USING 'en-GB')
/* Output: 2021-11-26 08:19:16 */
DECLARE #InString NVARCHAR(20)='26-11-2021 08:19:16';
SELECT #InString;
SELECT CONVERT(DATETIME,#InString,105);
Could you please try if it is suitable for you

Date conversion in a XML column in SQL Server

How do I convert the below mentioned XML code date format.
<StartDate>2015-12-24T00:00:00</StartDate>
<EndDate>2015-12-29T15:39:20</EndDate>
If you're accessing your XML content with the built-in XQuery functionality, you can just use the .value() method and define the output datatype to be a DATETIME2(3) type - no special treatment necessary:
DECLARE #InputTbl TABLE (ID INT NOT NULL, XmlContent XML)
INSERT INTO #InputTbl (ID, XmlContent)
VALUES (1, '<Root>
<StartDate>2015-12-24T00:00:00</StartDate>
<EndDate>2015-12-29T15:39:20</EndDate>
</Root>');
SELECT
StartDate = XC.value('(StartDate)[1]', 'datetime2(3)'),
EndDate = XC.value('(EndDate)[1]', 'datetime2(3)')
FROM
#InputTbl
CROSS APPLY
XmlContent.nodes('/Root') AS XT(XC)
This returns this output:
There are several correct answers, but I've got the feeling, that these answers don't hit your actual issue:
In my table there is a xml column, and that xml column contains somuch data including date, And i want to update those dates to date format like '2/28/2017' now the date format is like '2012-04-26T00:00:00'
If I got you correctly you want to change the stored dates within your XML to another format, correct?
Simple answer: Don't!
ISO8601 is the standard format for date/time values within XML. The format you would like more 2/28/2017 is culture related and could lead to errors, or even worse!, to wrong values, if day and month both are below 13: 04/05/2017 can be taken as 4th of May or as 5th of April. You should never rely on culture settings!
XML is not meant to be human readable. Or in better words: It is meant to be human readable for technical people only... It is a standardizes string representation of structured, complex documents. The format of values should not bother you! Use an appropriate editor for the presentation.
This might be work
declare #date ='2015-12-24T00:00:00 2015-12-29T15:39:20'
SELECT CONVERT(date, Left(#date,10)) as NewDate
This may help you
DECLARE #X XML ='<StartDate>2015-12-24T00:00:00</StartDate>
<EndDate>2015-12-29T15:39:20</EndDate>'
SELECT #X.value('/StartDate[1]','DATETIME') AS START_DTE
,#X.value('/EndDate[1]','DATETIME') AS END_DTE
+-------------------------+-------------------------+
| START_DTE | END_DTE |
+-------------------------+-------------------------+
| 2015-12-24 00:00:00.000 | 2015-12-29 15:39:20.000 |
+-------------------------+-------------------------+
Update: From comments
The Datatime format in XML follows the ISO8601 standards. And you are thinking to format it native SQL format, which is not correct that you are treating XML like normal text data. The data present in XML format is correct. And If you want you can convert it to native SQL as above mentioned.
There is a good info at Wikipedia ISO 8601(Combined date and time representations)
on how the XML hold date time data.
A single point in time can be represented by concatenating a complete
date expression, the letter T as a delimiter, and a valid time
expression. For example, "2007-04-05T14:30".

SQL Server: convert StartDATE 20140804 Nvarchar to Datetime2

I'm using SQL Server 2008 and I did an import from a flat file. I couldn't import the datetime column properly so I specified it temporarily as a nvarchar(50).
Now I want to convert it to datetime2 format. However when doing so, I get the error
Conversion failed when converting date and/or time from character string.
The data that is currently in my nvarchar(50) column looks like this:
20140804
And I need to convert it to:
2014-08-04 00:00:00.0000000.
Note that I do not only want to convert one date, but all StartDATE values in my table and insert them to another table
Any help is appreciated.
Insert into targettab(datecol,<othercols....>)
select cast(datefield as datetime2),<othercols...> from sourcetab
You can use cast function
you need to convert to char first because converting to int adds those days to 1900-01-01
select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))
here are some examples
select CONVERT (datetime,5)
1900-01-06 00:00:00.000
select CONVERT (datetime,20100101)
blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit
convert to char first
declare #i int
select #i = 20100101
select CONVERT (datetime,convert(char(8),#i))
SELECT convert(varchar, StartDATE , 113) from ur table

SQL Server Converting varchar to datetime

I got a problem in SQL Server with converting a varchar to datetime. I would like to convert/update whole column [datelog] in table:
[dd.mm.yyyy hh:mm:ss]` to `[yyyy-mm-dd hh:mm:ss]
In SQL Server 2012+ you can use PARSE or TRY_PARSE to parse a text value according to a specific culture.
Assuming your text follows the German culture ('de-DE') you can parse it to datetime with :
select PARSE('24.11.2015 13:10:55' as datetime using 'de-DE')
eg:
select PARSE(datelog as datetime using 'de-DE')
The real solution though would be to use the correct field type, ie datetime. It's almost guaranteed that someone, somewhere will either enter text with the wrong format or try to convert the text using the wrong culture.
Date types on the other hand, have no format, they are simply binary values. Using them is faster, safer and easier.
Tricky solution,
DECLARE #inputDate AS VARCHAR(20)='21.11.2015 06:59:00' -- [dd.mm.yyyy hh:mm:ss]
SET #inputDate = REPLACE(#inputDate ,'.' ,'/')
SELECT CONVERT(VARCHAR(24) ,CONVERT(DATETIME ,#inputDate ,103) ,121) OutputDate -- [yyyy-mm-dd hh:mm:ss]
Still you need to change as per your table columns.
temp table with one column of type varchar
create table #temp3 (someDate varchar (30))
insert into #temp3 values ('23.03.1989 15:23:43')
using a combination of concat, substring and right
select concat
(
SUBSTRING(someDate,7,4),'-', SUBSTRING(someDate,4,2),'-',SUBSTRING(someDate,1,2), ' ', right(someDate, 8)
)
from #temp3
gives: 1989-03-23 15:23:43

Which settings provide SQL Server default datetime format?

Say, I have a table like this :
Table name "DateTimeFormatCheck" >
I used below query to insert :
Insert into [dbo].[DateTimeFormatCheck] ([DateTimeCheck]) values('11/19/2014 1:29 PM')
It inserted date like 2014-11-19 13:29:00.000 , but my insertion format(M/d/yyyy h:m tt) is not same as inserted date.
Now i want to know How SQL Server detect my string date format that i have provided ? and Why it always provide this format yyyy-MM-dd HH:mm:ss after insertion?
Thanks
Don't do that! Don't use strings instead of dates and don't use a culture-specific date or datetime format, it's a recipe for disaster.
SQL Server doesn't have a "date format", just formats it uses to convert dates to and from strings. One of them is the default, controlled by the server's collation. You can neither assume nor should you depend on a specific collation, so you should avoid conversions whenever possible. Moreover, passing a string value can prevent SQL Server from using indexes on date columns because it would have to convert the string to the underlying column type.
It's far easier and safer to pass dates as date-typed variables or parameters. You avoid the entire conversion mess this way, to and from and avoid SQL injection attacks.
There's no reason to pass strings instead of dates to the server. All SQL Server clients (including ADO.NET) allow you to execute parameterized queries. ORMs like NHibernate and Entity Framework also generate parameterized queries for date-typed columns.
Whenever you need to create a string literal, use one of the invariant formats like 20140913 or 2012-11-07T18:26:20
You can read more about it at Writing International T-SQL Statements
The format of sqlserver is yyyy-mm-dd, but you can define your input by execute the command
set dateformat dmy -- to accept dmy format
set dateformat mdy
select cast( '11-9-2014' as date)
set dateformat dmy
select cast( '11-9-2014' as date)
updated
Ideally you can not try to change format, you can validate your data and then insert.
Whenever we insert into datetime datatype, sqlserver will implicitly try to convert into mmddyyy hhmmss format. so if you given date as 19/11/2014 , it convert into 11/19/2014 means 19th nov 2014.
But if you give more than 12 in the middle portion, it will not convert implicitly and throw the error of conversion.
Other than mmddyyyy format, you must use to cast or convert function explicitly to allow the data insert or update.
Before the casting you can use ISDATE or TRY_PRASE or PARSE function in sqlserver, will check to conversion possible or not.
you can create a function or just add line as
declare #dt varchar(50) = '19-11-2014 10:10:41'
declare #dTable table ( datecolumn datetime)
INSERT into #dTable values (
case
when isdate(CONVERT( varchar(50), #dt)) = 1 then CONVERT( varchar(50), #dt) --'19-11-2014 10:10:41'
when isdate(CONVERT( varchar(50), #dt, 103) ) = 1 then CONVERT( datetime, #dt , 103 ) --'19-11-2014 10:10:41'
when isdate(CONVERT( varchar(50), #dt, 102) ) = 1 then CONVERT( datetime, #dt , 102 ) --'19-11-2014 10:10:41'
--when --give other format as above given and if not set in any dateformat , then simply return null
else
null
end )
select * from #dTable

Resources