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

后端 未结 3 1442
被撕碎了的回忆
被撕碎了的回忆 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
    
    0 讨论(0)
  • 2021-01-17 01:44

    This should get the format you want... but there are probably better ways.

    select 
      convert(varchar(16),convert(date,left(ID,8)),101) + 
      ' ' + 
      substring(substring(ID,10,6),1,2) + 
      ':' + 
      substring(substring(ID,10,6),3,2) + 
      ':' + substring(substring(ID,10,6),5,2)
    
    0 讨论(0)
  • 2021-01-17 01:53
    Select CONVERT(VARCHAR(25) , CAST(LEFT(ID , 8) AS DATETIME), 101) 
           + ' ' +  LEFT(RIGHT(ID , 6) ,2) + ':' 
           + SUBSTRING(RIGHT(ID , 6) , 3,2) + ':' 
           + RIGHT(ID , 2) 
    FROM TableName 
    
    0 讨论(0)
提交回复
热议问题