Sql Server Date Format Yyyymmdd
I Have a Varchar Column Where Some Values Are in Mm/Dd/Yyyy Format and Some Are in Yyyymmdd. I Want to Convert All Mm/Dd/Yyyy Dates into the Yyyymmdd Format...
I have a varchar column where some values are in mm/dd/yyyy format and some are in yyyymmdd.
I want to convert all mm/dd/yyyy dates into the yyyymmdd format. What is the best way to do this? Thanks
Table is Employees and column is DOB
9 Answers
Assuming your "date" column is not actually a date.
Select convert(varchar(8),cast('12/24/2016' as date),112)
or
Select format(cast('12/24/2016' as date),'yyyyMMdd')
Returns
20161224
DECLARE @v DATE= '3/15/2013'
SELECT CONVERT(VARCHAR(10), @v, 112)
you can convert any date format or date time format to YYYYMMDD with no delimiters
try this....
SELECT FORMAT(CAST(DOB AS DATE),'yyyyMMdd') FROM Employees;
Select CONVERT(VARCHAR(8), GETDATE(), 112)
Tested in SQL Server 2012
You can do as follows:
Select Format(test.Time, 'yyyyMMdd')
From TableTest test
In SQL Server, you can do:
select coalesce(format(try_convert(date, col, 112), 'yyyyMMdd'), col)
This attempts the conversion, keeping the previous value if available.
Note: I hope you learned a lesson about storing dates as dates and not strings.
SELECT YEAR(getdate()) * 10000 + MONTH(getdate()) * 100 + DAY(getdate())
mm/dd/yyyy corresponds to U.S. standard so if you convert to date using 101 value and then to varchar using 112 for ISO date get the expected result.
declare @table table (date_value varchar(10))
insert into @table values ('03/30/2022'),('20220330')
select date_value
--converted to varchar
,case
--mm/dd/yyyy pattern
when patindex('[0,1][0-9]/[0-3][0-9]/[0-9][0-9][0-9][0-9]',date_value)>0 then convert(varchar(10),convert(date,date_value,101),112)
else date_value end date_value_new
--converted to date
,case
when patindex('[0,1][0-9]/[0-3][0-9]/[0-9][0-9][0-9][0-9]',date_value)>0 then convert(date,date_value,101)
else convert(date,date_value,112) end date_value_date
from @table
SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM table; //converts any date format to YYYY-MM-DD