'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. What is the best way to do this? Thanks
Table is Employees
and column is DOB
Solution 1:[1]
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
Solution 2:[2]
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
Solution 3:[3]
try this....
SELECT FORMAT(CAST(DOB AS DATE),'yyyyMMdd') FROM Employees;
Solution 4:[4]
Select CONVERT(VARCHAR(8), GETDATE(), 112)
Tested in SQL Server 2012
Solution 5:[5]
You can do as follows:
Select Format(test.Time, 'yyyyMMdd')
From TableTest test
Solution 6:[6]
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.
Solution 7:[7]
SELECT YEAR(getdate()) * 10000 + MONTH(getdate()) * 100 + DAY(getdate())
Solution 8:[8]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | John Cappelletti |
Solution 2 | |
Solution 3 | Ankitkumar Tandel |
Solution 4 | rchacko |
Solution 5 | mishsx |
Solution 6 | Gordon Linoff |
Solution 7 | Varun |
Solution 8 | Borja |