3/27/2019

How to create a Calendar table in SQL Server


Below Query to generate Calendar table based on given Start and End Date:


---------Code to generate Calendar table -----------

If OBJECT_ID('tempdb..#Calendar') IS NOT NULL DROP TABLE #Calendar

Declare @StartDate date

Declare @EndDate as Date

Select @StartDate = '2017-03-01'

Select @EndDate=  '2019-04-30'

 
CREATE TABLE #Calendar(

         CalendarMonthStart date PRIMARY KEY

       , CalendarMonthEnd date

       );

WITH

       t4 AS (SELECT n FROM (VALUES(0),(0),(0),(0)) t(n))

       ,t256 AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) - 1 AS num  FROM t4 AS a CROSS JOIN t4 AS b CROSS JOIN t4 AS c CROSS JOIN t4 AS d)

INSERT INTO #Calendar

SELECT
         DATEADD(month, num, @StartDate)

       , DATEADD(day, -1, DATEADD(month, num + 1, @StartDate))

FROM t256

WHERE

       num <= DATEDIFF(month, @StartDate, @EndDate);

       Select * from #Calendar


Below is output:

CalendarMonthStart CalendarMonthEnd
3/1/2017 3/31/2017
4/1/2017 4/30/2017
5/1/2017 5/31/2017
6/1/2017 6/30/2017
7/1/2017 7/31/2017
8/1/2017 8/31/2017
9/1/2017 9/30/2017
10/1/2017 10/31/2017
11/1/2017 11/30/2017
12/1/2017 12/31/2017
1/1/2018 1/31/2018
2/1/2018 2/28/2018
3/1/2018 3/31/2018
4/1/2018 4/30/2018
5/1/2018 5/31/2018
6/1/2018 6/30/2018
7/1/2018 7/31/2018
8/1/2018 8/31/2018
9/1/2018 9/30/2018
10/1/2018 10/31/2018
11/1/2018 11/30/2018
12/1/2018 12/31/2018
1/1/2019 1/31/2019
2/1/2019 2/28/2019
3/1/2019 3/31/2019
4/1/2019 4/30/2019

No comments:

Post a Comment

Tableau interview questions and answers for experienced professionals

  Tableau Interview Questions and Answers for experienced professional 1. What is TABLEAU? Tableau  is the powerful and fastest visualizing ...