Skip to content

Instantly share code, notes, and snippets.

@kmoormann
Created March 20, 2014 17:29
Show Gist options
  • Save kmoormann/9669275 to your computer and use it in GitHub Desktop.
Save kmoormann/9669275 to your computer and use it in GitHub Desktop.
SQL nugget to turn a datetime2 into a NVARCHAR as 'YYYY-MM-DD HH:MM:SS.mmm'
DECLARE @InsertDate DATETIME2
SET @InsertDate = GETDATE()
DECLARE @InsertDateString NVARCHAR(24)
SET @InsertDateString =
CAST(YEAR(@InsertDate) AS NVARCHAR(4))
+ '-'
+ CASE
WHEN MONTH(@InsertDate) < 10 THEN '0'
ELSE ''
END
+ CAST(MONTH(@InsertDate) AS NVARCHAR(2))
+ '-'
+ CASE
WHEN DAY(@InsertDate) < 10 THEN '0'
ELSE ''
END
+ CAST(DAY(@InsertDate) AS NVARCHAR(2))
+ ' '
+ CASE
WHEN DATEPART(HOUR,@InsertDate) < 10 THEN '0'
ELSE ''
END
+ CAST(DATEPART(HOUR,@InsertDate) AS NVARCHAR(2))
+ ':'
+ CASE
WHEN DATEPART(MINUTE,@InsertDate) < 10 THEN '0'
ELSE ''
END
+ CAST(DATEPART(MINUTE,@InsertDate) AS NVARCHAR(2))
+ ':'
+ CASE
WHEN DATEPART(SECOND,@InsertDate) < 10 THEN '0'
ELSE ''
END
+ CAST(DATEPART(SECOND,@InsertDate) AS NVARCHAR(2))
+ '.'
+ CASE
WHEN DATEPART(MILLISECOND,@InsertDate) < 10 THEN '00'
WHEN DATEPART(MILLISECOND,@InsertDate) < 100 THEN '0'
ELSE ''
END
+ CAST(DATEPART(MILLISECOND,@InsertDate) AS NVARCHAR(3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment