I have date stored in varchar in SQL Server as '19-09-2020' and I want to convert it to '2020-09-19' - sql

I have date stored in a varchar column in SQL Server as '19-09-2020'.
I want to convert it to '2020-09-19'.
I have tried this but it's not working:
select convert(varchar, '19-09-2020', 23)

You must specify the source format for convert:
convert(date, '19-09-2020',105)
This results in a DATE, if you actually want a VarChar again (of course, you shouldn't):
convert(varchar(10), convert(date, '19-09-2020',105), 23)

Do you want string functions?
select concat_ws('-', right(mycol, 4), substring(mycol, 4, 2), left(mycol, 2))
from mytable
On the other hand, if you want to generate a date from that string, then:
select convert(date, mycol, 105)
from mytable

Related

Formatting date issue

I have the following query:
SELECT ACCOUNTNUMBER, PROCESSDATE
FROM INVENTORY
Result:
ACCOUNT PROCESSDATE
5646546 11082021
4654646 11082021
The date is in the wrong format.
NOTE: I checked the table design and the PROCESSDATE field seems to be an integer.
What code I have tried:
.-format(PROCESSDATE, 'DD/mm/yyyy') as PROCESSDATE [the result is DD/mm/yyyy in the column)
.-CONVERT(date, CONVERT(varchar(6), PROCESSDATE) + '01') myDate [The result is an error]
.-CONVERT(CHAR(10), PROCESSDATEAS Datetime) as 'MyDateTime' [the result is an error]
Desired output: Obtain PROCESSDATE field as MM/dd/yyyy format.
This is a horrible format. Note that if the day is less than 10, then the length of the integer changes. Arggh!
So, my recommendation is to convert to an 8-character string (with a leading '0' if necessary), then construct a canonical date string ('YYYYMMDD'). And convert to a date:
select convert(date,
right(format(processdate, '00000000'), 4) + substring(format(processdate, '00000000'), 3, 2) +left(format(processdate, '00000000'), 2)
)
You can actually move the format() to a subquery, CTE, or values clause, as in:
select convert(date, right(v.processdate_str, 4) + substring(v.processdate_str, 3, 2) +left(v.processdate_str, 2))
from inventory i cross apply
(values (format(i.processdate, '00000000'))
) v(processdate_str)
Here is a db<>fiddle.
You could use DATEFROMPARTS to parse the parts and then format 101 to put in MM/DD/YYYY format. Something like this
SELECT ACCOUNTNUMBER,
PROCESSDATE,
calc.dt,
convert(varchar(12), calc.dt, 101) vc_with_date_format
FROM (values (5646546, 11082021),
(5646546, 11082021))
INVENTORY(ACCOUNTNUMBER, PROCESSDATE)
cross apply (values (datefromparts(right(PROCESSDATE, 4),
substring(cast(PROCESSDATE as char(8)),3,2),
left(PROCESSDATE, 2)))) calc(dt);
[EDIT] Without the virtual table (which was for demo only)
SELECT i.ACCOUNTNUMBER,
i.PROCESSDATE,
calc.dt,
convert(varchar(12), calc.dt, 101) vc_with_date_format
FROM INVENTORY i
cross apply (values (datefromparts(right(i.PROCESSDATE, 4),
substring(cast(i.PROCESSDATE as char(8)),3,2),
left(i.PROCESSDATE, 2)))) calc(dt);
ACCOUNTNUMBER PROCESSDATE dt vc_with_date_format
5646546 11082021 2021-08-11 08/11/2021
5646546 11082021 2021-08-11 08/11/2021
I think your dates are stored as ddMMyyyy in the DB. You can get the desired result by applying the following conversion:
CONVERT(VARCHAR, CONVERT(DATETIME,STUFF(STUFF(PROCESSDATE, 5, 0, '/'), 3, 0, '/'),103), 101)

How to convert SQL string date to usable ISO8601 date?

I have a query that I need to check if one date is less than or equal to another. The date is stored in the table as a string in this format 2/1/2020 The SQL Server version on my testing server is 13.0 and the query below works fine but both staging and production is version 11.0.7. Below query is what I have tried so far but get an error
"Conversion failed when converting date and/or time from character string.".
What is the correct way to write this query so that it works on all of the SQL servers?
SELECT TrackingNumber
FROM CarrierTrackingData
WHERE (SUBSTRING(Status, 1, 9) = 'Delivered') AND (CONVERT(date, CAST(DeliveryDate AS date), 23) <= CONVERT(date, CAST(InStoreDate AS date), 23))
GROUP BY TrackingNumber```
You need 101 century mm/dd/yyyy to convert into date format :
WHERE ( SUBSTRING(Status, 1, 9) = 'Delivered' AND
CONVERT(date, DeliveryDate , 101) <= CONVERT(date, InStoreDate , 101)
);
Note : You don't need to use CAST() as CONVERT() with century will do conversation for you.
EDIT : You can check the possible date format using TRY_CONVERT() :
SELECT DeliveryDate,
TRY_CONVERT(DATE, DeliveryDate, 101) AS Possible_DeliveryDate,
InStoreDate,
TRY_CONVERT(DATE, InStoreDate , 101) AS Possible_InStoreDate
FROM table t;
TRY_CONVERT() will return NULL where the conversation fails.

Varchar date to datetime sql

I have a varchar date format of 01012018, I need to convert this to a date in a SQL Server view:
CONVERT(VARCHAR(50), CONVERT(DATE, [Date], 103), 103)
I have tried the above with no joy.
Please help
SQL Server can be a bit cumbersome when parsing dates that are not one of the "built-in" ones. You can use parse()/try_parse(), but that is a relatively new function.
In your case, it is pretty simple to construct the date value directly:
select convert(date, concat(right(ddmmyyyy, 4), substring(ddmmyyyy, 3, 2), left(ddmmyyyy, 2)))
from (values ('01012018')) v(ddmmyyyy)
There is no style ddMMyyyy in the CONVERT Date and Time Styles, but there is a dd/MM/yyyy, so you could inject these characters in and convert:
SELECT TRY_CONVERT(date, STUFF(STUFF(v.ddmmyyyy, 5, 0, '/'), 3, 0, '/'), 103)
FROM (VALUES ('01012018')) v (ddmmyyyy);
I've also used TRY_CONVERT incase you have some other "bad" values (perhaps '01312019'). These will return NULL when the varchar represents an invalid date.
Use CONVERT() as
DECLARE #Var VARCHAR(10) = '01012018'
SELECT CONVERT(DATE,
CONCAT( RIGHT(#Var, 4),
SUBSTRING(#Var, 3, 2),
LEFT(#Var, 2)
)
)
Demo
Finally, I would recommend ALTERing your table (which is the right solution) and change the data type of your column to DATE data type.
CREATE TABLE T(
MyCol VARCHAR(10)
);
INSERT INTO T(MyCol) VALUES
('01012018'),
('01022018'),
('01032018'),
('WrongData');
SELECT MyCol
FROM T;
UPDATE T
SET MyCol = TRY_CONVERT(DATE,
CONCAT( RIGHT(MyCol, 4),
SUBSTRING(MyCol, 3, 2),
LEFT(MyCol, 2)
)
);
ALTER TABLE T
ALTER COLUMN MyCol DATE;
SELECT MyCol
FROM T;
Second Demo

SQL Server - How to convert varchar to date

I have a table containing StartDate in the format dd/mm/yyyy and yyyy-mm-dd.
I want to convert this varchar column to DATE type in the format DD/MM/YYYY.
I have tried the below.
select CONVERT(varchar(20),StartDate,103) AS [FormattedDate]
and
CONVERT(VARCHAR(20),(CAST([StartDate] AS DATE)),103)
I get the error -Conversion failed when converting date and/or time from character string.
Pls suggest.
if you only have the date string in dd/mm/yyyy or yyyy-mm-dd
select case when substring(StartDate, 3, 1) = '/'
then convert(date, StartDate, 103)
else convert(date, StartDate, 121)
end
SQL Server is actually quite good about figuring out formats for a date conversion with no formatting argument. However, it is going to assume MM/DD/YYYY for the second format and generate an error.
So, you can use try_convert() and coalesce():
select coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
)
Here is a SQL Fiddle.
Then, you should go into your data and fix the column. Here is one method:
update t
set startdate = coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
);
alter table t alter column startdate date;
You can add additional formatting for the result set by turning the date back into a string, using convert().
To get YYYY-MM-DD use SELECT CONVERT(varchar, getdate(), 23)
To get MM/DD/YYYY use SELECT CONVERT(varchar, getdate(), 1)
For detailed explaination try this.
Here's an example that first tries to convert the VARCHAR from a 'yyyy-mm-dd' format to the 'dd/mm/yyyy' format.
If that doesn't work out, then it just assumes it's already in the 'dd/mm/yyyy' format.
And then defaults to the first 10 characters from the string.
declare #TestTable table (StartDate varchar(10), DateFormatUsed varchar(10));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate() ,103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
;
select t.*,
coalesce(convert(varchar(10), try_convert(date,StartDate,20),103), left(StartDate,10)) as [FormattedDate]
from #TestTable t;
But try_convert is only available since MS SQL Server 2012.
For MS SQL Server 2008 we can use a CASE WHEN with a LIKE to check the format.
declare #TestTable table (StartDate varchar(30), DateFormatUsed varchar(30));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate(), 103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
,(convert(varchar(19),GetDate(), 20), 'yyyy-mm-dd hh:mi:ss')
;
select t.*,
(case
when StartDate like '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'
then convert(varchar(10), convert(date, left(StartDate, 10), 20), 103)
else left(StartDate, 10)
end) as [FormattedDate]
from #TestTable t;

How to Convert nvarchar (including time) into datetime

I have data 20160526094432, and I want to convert into datetime in SQLServer
The result will be 2016-05-26 09:44:32
Is there simple way to do that ?
Thanks
If you use MS SQL Server 2012 or newer then you can enjoy format function.
select cast(format(20160526094432,'####-##-## ##:##:##') as datetime) [date-time]
If your long number is a string then you have to convert it.
declare #d varchar(20)='20160526094432'
select cast(format(cast(#d as bigint),'####-##-## ##:##:##') as datetime) [date-time]
Hmmm. I don't think there is a really clean way, but something like this should work:
select (convert(datetime, left(col, 8) as datetime) +
convert(datetime, convert(time,
stuff(stuff(right(col, 6), 5, 0, ':'), 3, 0, ':')
)
)
)
Maybe you can try in this way, for example Date is the column of your table, 103 is the format of Date you want to convert, google for more details.
CONVERT(datetime, Date, 103)