Created
March 20, 2014 17:29
-
-
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'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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