Files
sql-snippets/cal-ca9ed7a3-6fb0-4d39-b918-887951161076.json
2023-08-23 14:49:46 +02:00

6 lines
1.3 KiB
JSON

{
"id": "ca9ed7a3-6fb0-4d39-b918-887951161076",
"prefix": "cal",
"description": "create a calendar #cal table",
"body": "DECLARE @dtmFrom DATETIME, @dtmTo DATETIME;\r\nSELECT @dtmFrom = '20100812', @dtmTo=CURRENT_TIMESTAMP\r\n\r\n--#region create calendar\r\nDECLARE @nb TABLE( val INT);\r\nINSERT INTO @nb(val)\r\nSELECT a=0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9;\r\n\r\nIF (SELECT OBJECT_ID('tempdb..#cal'))IS NOT NULL BEGIN\r\n\tDROP TABLE #cal;\r\nEND; \r\n\r\nSELECT \r\n --+1 to take the current day, must be reflected in the TOP subquery\r\n DATEADD(DAY, (x.[nbr] * -1) + 1, CURRENT_TIMESTAMP) AS dt\r\nINTO #cal\r\nFROM(\r\n SELECT * \r\n FROM (\r\n --the TOP limits the calendar to the specified days. +1 to compensate the current day in DATEADD()\r\n SELECT TOP (DATEDIFF(DAY, @dtmFrom, @dtmTo)+1)\r\n ROW_NUMBER()OVER(ORDER BY a.val) AS nbr\r\n FROM @nb a\r\n CROSS JOIN @nb b\r\n CROSS JOIN @nb c\r\n CROSS JOIN @nb d\r\n CROSS JOIN @nb e\r\n CROSS JOIN @nb f\r\n ORDER BY a.[val]\r\n )tally\r\n)x\r\n--#endregion\r\n\r\nSELECT MIN([c].[dt]), MAX([c].[dt])\r\nFROM [#cal] c"
}