You can make it a little more compact by not forcing the dashes, and using STUFF
instead of SUBSTRING
:
DECLARE @Var VARCHAR(100) = '20130120161643730';
SET @Var = LEFT(@Var, 8) + ' '
+ STUFF(STUFF(STUFF(RIGHT(@Var, 9),3,0,':'),6,0,':'),9,0,'.');
SELECT [string] = @Var, [datetime] = CONVERT(DATETIME, @Var);
Results:
string datetime
--------------------- -----------------------
20130120 16:16:43.730 2013-01-20 16:16:43.730