![]() |
Database »
Database »
SQL Server
Beginner
License: The Code Project Open License (CPOL)
Get a table with all dates in a monthBy TDunkThis SQL Server 2005 Table values function returns a table with all dates of a month for a provided date. |
SQL, Windows, SQL Server (SQL 2005)
|
||||||||
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
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.
The function "getFullmonth" looks like this:
-- =============================================
-- 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:
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.
The same princip can be used for returning all day numbers in a week.
Happy coding!
Version 1.0
| You must Sign In to use this message board. | ||||||||||||||||||||||
|
||||||||||||||||||||||
|
||||||||||||||||||||||
|
||||||||||||||||||||||
|
||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 7 Mar 2008 Editor: |
Copyright 2008 by TDunk Everything else Copyright © CodeProject, 1999-2009 Web09 | Advertise on the Code Project |