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
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
.
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
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)
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