Click here to Skip to main content
15,884,176 members
Articles / Database Development / SQL Server
Article

Get a table with all dates in a month

Rate me:
Please Sign up or sign in to vote.
1.33/5 (3 votes)
7 Mar 2008CPOL 33.5K   15   4
This SQL Server 2005 Table values function returns a table with all dates of a month for a provided date.

Introduction

When doing different joins it's often usefull to have a table that contains all dates in a specific month.

This is af table-valued function for SQL Server 2005 that creates such a table.

Using the code

The function "getFullmonth" looks like this:

SQL
-- =============================================
-- Description: Returns a table containing all dates in the month of the specified date
-- =============================================
ALTER FUNCTION [dbo].[getFullmonth]
(
 @date1 datetime
)
RETURNS @dates TABLE 
(
 date datetime not null 
)
AS
BEGIN
 -- Set first day in month
 DECLARE @month int;
 
 SET @month = datepart(MM, @date1);
 SET @date1 = convert(datetime, convert(varchar,datepart(yy,@date1)) + '.' + convert(varchar,@month) + '.01 00:00:00');
 WHILE datepart(MM,@date1) = @month
 BEGIN
  INSERT INTO @dates VALUES (@date1);
  SET @date1 = dateadd(dd, 1, @date1);
 END 
 RETURN;
END                      

After creating the function it can be used like this for different queries:

SQL
SELECT a.date, b.holidayname 
FROM dbo.getFullmonth(getdate()) a 
LEFT OUTER JOIN holiday b on a.date = b.holidaydate
ORDER BY 1, 2

If the above table "holiday" holds all public holidays the result will show the full month with the name for the holidays in the current month.

Points of Interest

The same princip can be used for returning all day numbers in a week.

Happy coding!

History

Version 1.0

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer TimeMap ApS
Denmark Denmark
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralThanks a lot Pin
Cum7me15-Dec-13 23:45
Cum7me15-Dec-13 23:45 
QuestionCan also use CTE in SQL 2005 Pin
Graham H.2-Apr-08 13:31
Graham H.2-Apr-08 13:31 
GeneralIt is possible to do this without using a table variable Pin
Noam Helfman10-Mar-08 10:07
Noam Helfman10-Mar-08 10:07 
GeneralWeak Pin
Not Active7-Mar-08 4:46
mentorNot Active7-Mar-08 4:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.