Wednesday, January 4, 2017

Create Calendar Table in Sql Server 2008

Hi, Wish a very very Happy New Year!Now we’ll see this new year calendar in  SQL Server.

Just copy the below code and Execute it on SQL Editor...

USE tempdb

IF EXISTS
      (SELECT * FROM sys.objects WHERE name = 'Calendar' AND type = 'U')
      --(SELECT * FROM information_schema.tables WHERE Table_Name = 'Calendar' AND Table_Type = 'BASE TABLE')
BEGIN
      DROP TABLE [Calendar]
END

      CREATE TABLE [Calendar] ([CalendarDate] DATE, [WeekDay] VARCHAR(10))

      DECLARE @StartDate DATETIME = '20170101'
      DECLARE @EndDate DATETIME = '20171231'    --DATEADD(d, 365, @StartDate)

WHILE @StartDate <= @EndDate
      BEGIN
             INSERT INTO [Calendar] ([CalendarDate],[WeekDay])
                         
             SELECT @StartDate, DATENAME (DW,@StartDate)

             SET @StartDate = DATEADD(dd, 1, @StartDate)
      END

SELECT CONVERT(VARCHAR(10),CalendarDate,103)'DATE',* FROM [Calendar] ORDER BY [CalendarDate]  


If there is any other better option,
Please share it here or mail to me arkaa4@gmail.com

Thank You,
Arka Gupta.

No comments:

Post a Comment