SQL Server: Transfer YYYYMMDD-HHMMSS to mm/dd/yyyy hh:mm:ss

后端 未结 3 1441
被撕碎了的回忆
被撕碎了的回忆 2021-01-17 01:15

My SQL Server system is 2016.

As topic, I want to convert YYYYMMDD-HHMMSS to mm/dd/yyyy hh:mm:ss, and use dynamic SQL to fulfill this.

My da

3条回答
  •  借酒劲吻你
    2021-01-17 01:29

    Try it like this

    DECLARE @tbl TABLE(ID NVARCHAR(100));
    INSERT INTO @tbl VALUES
     ('20161119-075950')
    ,('20161117-110952')
    ,('20161118-153406');
    

    --This is the actual select you need:

    SELECT CAST(LEFT(ID,8) AS DATETIME) + STUFF(STUFF(RIGHT(ID,6),5,0,':'),3,0,':')
    FROM @tbl
    

    Your first part is strictly 8 chars long and implicitly casteable (unseperated datetime yyyymmdd). The time part is strictly 6 chars long. I use STUFF to insert the colons. This time can be added to a DATETIME. It will be - again implicitly - casted to DATETIME.

    EDIT

    To reach the given format you stated in the title just convert the first part first with code 101:

    SELECT CONVERT(VARCHAR(10),CAST(LEFT(ID,8) AS DATETIME),101) + ' ' + STUFF(STUFF(RIGHT(ID,6),5,0,':'),3,0,':')
    FROM @tbl
    

提交回复
热议问题