Parse a date from unformatted text in SQL

前端 未结 4 1503
执笔经年
执笔经年 2020-12-11 02:44

I\'m trying to figure out an elegant way to get a date from a text column that has data like this \"YYYYMMDD\"...so we might see \"20060508\" as a value in the column, which

4条回答
  •  青春惊慌失措
    2020-12-11 03:50

    This is already a valid date - ISO-8601 format - just use:

    SELECT CAST('20060508' AS DATETIME)
    

    or alternatively:

    SELECT CONVERT(DATETIME, '20060508', 112)
    

    and that should do just fine!

    In order to get your "May 08, 2006" display, do another convert into varchar, using the date convert style 107:

    SELECT CONVERT(VARCHAR(25), CAST('2006-05-08' AS DATETIME), 107)
    

    See here for more information on casting & converting in MS SQL

提交回复
热议问题