Search code examples
sqlsql-servert-sqldatetime-conversion

Convert string in T-SQL (YYYMMDD)


I have a column exit_date with varchar like 5/21/2008 0:00 and I need to update it to a string like YYYYMMDD, any way to do that?

5/21/2008 0:00  ==> 20080521  
1/1/2007 0:00   ==> 20070101

How to do something like

select convert('5/21/2008 0:00', 'YYYYMMDD').

Solution

  • CONVERT allows a style for conversions datetime/varchar in both directions. Saying that, you have a format that is not listed. And you actually have 2 conversions too: you need to get it into datetime first

    In my local SQL install that has the default "us_english" settings, this works out of the box

    select convert(datetime, '5/21/2008 0:00')
    

    thus

    select convert(char(8), convert(datetime, '5/21/2008 0:00'), 112)
    

    You can use SET LANGUAGE to modify to us_english temporarily