forked from DavidWiseman/sqlserver-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Date_Format_Cheat_Sheet.sql
69 lines (53 loc) · 1.68 KB
/
Date_Format_Cheat_Sheet.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
Author: Aaron Bertrand
Original links: https://www.mssqltips.com/sqlservertip/4052/build-a-cheat-sheet-for-sql-server-date-and-time-formats/
*/
SET NOCOUNT ON;
DECLARE @sql NVARCHAR(MAX), @v VARCHAR(30), @d DATETIME2(7), @sqlServerMajorVersion TINYINT;
SET @sql = N'';
-- a random date/time, making sure no single digits for any
-- date parts as these can truncate length of output:
SET @d = '2015-12-31T22:25:59.7901245';
SET @sqlServerMajorVersion = CAST(SERVERPROPERTY ('ProductMajorVersion') AS TINYINT);
CREATE TABLE #s(style VARCHAR(3));
-- for SQL Server < 2012
IF @sqlServerMajorVersion < 12
BEGIN
DECLARE @s INT = 0;
WHILE @s <= 255
BEGIN
BEGIN TRY
SET @sql = N'SELECT @v = CONVERT(VARCHAR(30), @d, ' + RTRIM(@s) + ');';
EXEC sys.sp_executesql @sql, N'@v VARCHAR(30), @d DATETIME2(7)', @v, @d;
INSERT #s(style) VALUES(@s);
END TRY
BEGIN CATCH
SET @sql = N'';
END CATCH
SET @s = @s + 1;
END
END
-- for SQL Server >= 2012
ELSE
BEGIN
SET @sql = N'';
WITH x(rn) AS
(
SELECT TOP (256) CONVERT(VARCHAR(3), ROW_NUMBER() OVER (ORDER BY name) - 1)
FROM sys.all_objects ORDER BY name
)
SELECT @sql = @sql + N'INSERT #s SELECT ' + rn + ' FROM
(SELECT n = TRY_CONVERT(VARCHAR(30),@d,' + rn + ')) AS x
WHERE n IS NOT NULL;' FROM x;
EXEC sys.sp_executesql @sql, N'@d DATETIME2(7)', @d;
END
SET @sql = N'';
SELECT @sql = @sql + N' UNION ALL SELECT [style #] = '
+ style + ', expression = N''CONVERT(CHAR(''
+RTRIM(LEN(CONVERT(VARCHAR(30), @d, ' + style + ')))
+''), @d, ' + style + ')'',
[output] = CONVERT(VARCHAR(30), @d, ' + style + ')'
FROM #s;
SET @sql = STUFF(@sql, 1, 11, N'') + N';';
EXEC sys.sp_executesql @sql, N'@d DATETIME2(7)', @d;
DROP TABLE #s;