Build a T-SQL Calendar using SQL Function GetFullMonth on MS SQL Server
User Defined SQL Function GetFullMonth
SQL Server t-sql developers or administrators can use the below user defined function in order to list the calendar dates within a month.
We can pass the date as a parameter to the t-sql calendar date function and list the sql dates which belongs to the month of the given parameter date value.
You can alter the following t-sql function code as you wish in order to your requirements. For example, you can only pass the month.
You can further alter the function to pass two date parameter values and list the calendar dates within the given sql date range instead of listing only dates in a given month.
For this t-sql task you can use the dbo.DateTable function which is demonstrated at How to Create a Date Table or a SQL Server Calendar Table using CTE T-SQL Code titled article.
And the output of the dbo.GetFullMonth function can be seen with a sample t-sql SELECT statement as follows:
How to Query SQL Server for T-SQL Calendar using GetFullMonth using PIVOT
After listing sql calendar date values in a month as rows, we need to display them now in a format similar to frequently used in printed calendars.
The day names are listed as column names and dates are shown under the related columns.
The first solution is supplied by Plamen Ratchev from SQLStudio.com using the t-sql PIVOT. Since I liked the t-sql code he coded much I want to share it with you here.
And the output of this sql pivot statement will return the following result set as output which is displaying sql dates in a calendar format.
Alternative Method for Building SQL Calendar Week Based using CTE
I have also developed a solution of mine, but using simple t-sql CTE instead of t-sql PIVOT statements.
Both methods are actually ending with the same result set.
Here is the sample t-sql code for the t-sql calendar listing.
Here is the CTE output for generating sql calendar dates on a MS SQL Server 2005 or later (SQL Server 2008).