SQL - Unable to Convert a string in to YYYYMMDD format - sql

I have a table that one of its columns is XML data type.
This XML value includes a TimePeriod value that looks like this:
"{start:{align:'Start',date:'2011-05-20T00:00:00'}"
I managed to extract only the date from this string with the following query:
SELECT SUBSTRING(configuration.value('(/ActiveService/#TimePeriod)[1]','nvarchar(50)'),
CHARINDEX('''', configuration.value('(/ActiveService/#TimePeriod)[1]','nvarchar(50)'),28)+1,10 )
FROM [MySystem].[dbo].[MyServices]
so i got this as the result: 2013-11-01
But, now i need to convert it to this format: YYYYMMDD
And when I'm using CONVERT to format 112 I Still get the same result: 2013-11-01
Why?

It you took value from xml as varchar, you cannot convert it into format YYYYMMDD (because it's already varchar), you have to convert it to date (or datetime first):
select convert(varchar(8), convert(datetime,
substring(
#data.value('(/ActiveService/#TimePeriod)[1]','nvarchar(50)'), 29, 10
), 120), 112)
But in your case it could be easier just remove -, by replace(<your value>, '-', '').
sql fiddle demo

Related

Change date time format from YYY-MM-DD HH:MM:SS to YYYY.MM.DD HH:MM:SS in SQL Server

I have a table with a column RequestDate with following format 2019-12-01 00:00:00:000. I want to see results like this: 2019.12.01 00:00:00:000.
I used this command
SELECT CONVERT(char(10), RequestDate, 104) AS finaldate
From the above query I am seeing results as 2019.12.01, but I am missing time (00:00:00:000) - how can I keep along with time. I want final results like 2019.12.01 00:00:00:000
I don't think that there is a built-in format specifier for this. But you could do:
replace(convert(varchar, requestDate, 121), '-', '.')
121 gives you format YYYY-MM-DD HH:MM:SS.SSS. You can then replace each occurence of '-' with ':'.
Note that this assumes that you have a datetime datatype to start with. If you have a string, then no need to convert(), you can just replace().

T-SQL - Convert datetime to unseparated ISO value

I'm trying to convert the following DATETIME into ISO format:
-- Today's Date
2018-04-16 2:04PM
I plan on parsing this into a char value as NVARCHAR so that I can concatenate it as part of a string.
Desired result should be:
-- Date and time unseparated
20180416140422
After some research I discovered here that
CONVERT(datetime, GETDATE(), 112)
using the 112 format code should get me the format I want but somehow I get the following sample output:
--Formatted using 112 format
Apr 16 2018 2:04PM
Why is this? I simply want to format the DATETIME object unseparated.
Also how would I do this with or without the time tagged onto the end?
Using SQL Server 2008R2
It should be :
select CONVERT(varchar(20), GETDATE(), 112)
Output
20180416
If you want date & time both, then can try using this :
select CONVERT(varchar(20), GETDATE(), 112) + replace(CONVERT(varchar(20), GETDATE(), 108), ':', '')
Output
20180416193327
Something like:
--20180416152520
SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), GETDATE(), 121), '-', ''), ':', ''), ' ', '') AS DesiredFormat
Output:
20180416152520
Check this out:
SELECT CONVERT(varchar(20), GETDATE(), 112) AS ISODate
, CONVERT(varchar(50), GETDATE(), 126) AS ISOWithTime_WorksWithAnyLanguageSetting;
I believe the names of the columns are self-explanatory.
Output example:
ISODate | ISOWithTime_WorksWithAnyLanguageSetting
------------------------------------------------------
20180416 | 2018-04-16T15:26:50.607
For information on more formats of the CONVERT function with examples check this source.
These all seem a bit overly cumbersome when all you need is format():
select format(getdate(), 'yyyyMMddHHmmss') as ISODateTime;

Issue with Date format in SQL

I am currently using SQL Server 2008. I am extracting a column F254 value from a SQL query where it is returning the date format in MM/DD/YYYY (e.g. 8/17/2017).
I need the output to be in format YYYYMMDD (e.g. 20170817).
Note that the column F254 is of datatype char(10) and I cannot change the datatype.
I have tried below but the getting the needed output
H.F254 AS Original_Date, --> 8/17/2017
CONVERT(VARCHAR(10), H.F254, 111) AS eg1, --> 8/17/2017
REPLACE(CONVERT(VARCHAR(10), H.F254, 103), '/', '') AS eg2 -->8172017
CONVERT(VARCHAR(9), H.F254, 112) AS eg3 --> 8/17/2017
I have also checked the following Date Format but its not working
I think you have to convert it to a date first!
select convert(varchar(10),cast(H.F254 as date),112)

Concatenate String + date in SQL Server

I have the following data:
KEY ID DATE
123456789 09BA2038 01-01-2017
And I would like to concatenate it, but keep the original format of the date. When I try:
CONCAT(Key, '-', ID, '-', DATE)
it gives me an output of
123456789-09BA2038-Jan 01 2017 11:00AM
But I would like the output to be
123456789-09BA2038-01-01-2017
If you're using SQL Server 2012 or newer, then you can use FORMAT to change a date or datetime into a varchar with the format of your liking.
select CONCAT([Key],'-',ID,'-',FORMAT([DATE],'MM-dd-yyyy')) as Key2
from (values (123456789,'09BA2038',convert(date,'2017-01-15',126))) v([Key],ID,[DATE]);
Result:
Key2
123456789-09BA2038-01-15-2017
Or you could use CONVERT instead using the 110 style for the USA date format.
Convert the date, I am guessing you want the format mm-dd-yyyy, if so:
CONCAT([key],'-',[ID],'-',CONVERT(VARCHAR(10), [DATE], 110))
If you want dd-mm-yyyy it is:
CONVERT(VARCHAR(10), [DATE], 105)
You need to use an explicit convert to get the date format you want.
In this case CONCAT(Key, '-', ID, '-', convert(varchar(10),DATE,105)) should work fine.
You can find the full list of formats here: https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
Try CONCAT(Key, '-', ID, '-', CONVERT(varchar(10),DATE, 110)). The 110 tells SQL Server to format the date as 'mm-dd-yyyy' (US style).
For more information about this look here.
Niels
I think not using concat is better in this situation
like this:
select convert(nvarchar(100),KEY)+'-'+convert(nvarchar(100),ID)+'-'+convert(nvarchar(100),DATE)
from tableName

Convert to DATE T-SQL

I have a field with date in the format dd.mm.yyyy E.x. 29.05.2016. I want to SELECT it as DATE but I get an error when I try the following:
CAST([PublishedDate] AS DATE) AS PublishedOn
Conversion failed when converting date and/or time from character string.
Reading this I tried the following:
CONVERT(VARCHAR(10), [PublishedDate], 126) AS PublishedDate
But it doesn't change the format.
How do I SELECT to have it in YYYY-MM-DD format.
EDIT: I have 3 different date fields with all three having different formats: dd.mm.yyyy | yyyy-mm-dd | yyyy/mm/dd. I want to select all of them with the same format. Since I use this query to build reports, right now I have dates in different formats. Doing the following:
CONVERT(VARCHAR(10), [PublishedDate], 104) AS PublishedOn
CONVERT(VARCHAR(10), [ValidFromDate], 104) AS ValidFrom
Gives me the following
You should use the right format, in your case it would be:
CONVERT(date, [PublishedDate], 104) AS PublishedDate
Also, once it's in a date, datetime or other date datatype, it doesn't have a format at all.
edit: Once you have your values in a date datatype, of course you can recast to a varchar to get the visual representation of the date you need.
edit2: If you want a date datatype, you should convert to date: CONVERT(DATE, [your column], [your format]).
If you want a nvarchar datatype, you should convert to nvarchar: CONVERT(nvarchar(x), [your column], [your format]).
You have an nvarchar that you want to display in a certain format, so you should first convert to date, then back to varchar (I doubt you need unicode):
CONVERT(VARCHAR(10), CONVERT(date, [PublishedDate], 104), 126)
The 104 you have to change for columns that are currently in a different format.
The best solution by far, is to change the datatypes to date. That is a bit of work, but definitely worthwhile.
If you really want the string do like this:
CONVERT(char(10), CONVERT(date,[date], 104),126) AS PublishedDate
Convert the string to date, using the 104 format (dd.mm.yyyy), as it is your original format, then convert the date into string, using the 126 format (yyy-mm-dd)
If you have a newer version of SQL Server, you may try
SELECT COALESCE(TRY_CAST(adate AS DATE), TRY_convert(DATE, adate, 126), TRY_convert(DATE, adate, 104)), format
FROM (
VALUES ('26.04.2017', 'dkformat') ,
('01.01.2017', 'EU format'),
('12.12.12', 'unknown format')
) a(aDate, format)
But you are going down a dangerous path, when you are trying to guess what format your source is in. Been there, done that, had the t-shirt.
I still hate the 0.1% conversions that are wrong.
This solution will result in NULLs, so you can see where your conversion did not succeed.