Monday, October 25, 2010

Function to return all dates consisting of n(th) week of the specific day

-- =============================================
-- Description: function to return date
-- Select * from dbo.GetAllDate(2009,5,5)
-- =============================================
CREATE FUNCTION [dbo].[GetAllDate]
(
@year INT, -- Year of Date
@number SMALLINT, -- (n)th Week of Date
@day SMALLINT -- Day of Date
)
RETURNS @ReturnTbl TABLE
(
Dates DATETIME
)
AS
BEGIN
/*
@day variable can be :
1: Sunday
2: Monday
3: Tuesday
4: Wednesday
5: Thursday
6: Friday
7: Saturday
*/

IF @number > 5
BEGIN
SET @number = 5
END

DECLARE @start_date DATETIME, @retrunDate DATETIME, @month_counter TINYINT

SET @month_counter =1

WHILE (@month_counter < = 12)
BEGIN
SET @start_date = CAST(CAST(@year AS VARCHAR(4)) + '-' + CAST(@month_counter AS VARCHAR(4)) + '-01' As SmallDateTime)

IF(MONTH(DATEADD(DAY,@day-DATEPART(DW,@start_date),@start_date))=@month_counter)
BEGIN
IF(MONTH(DATEADD(WEEK,@number-1,DATEADD(DAY,@day-DATEPART(DW,@start_date),@start_date)))=@month_counter)
SELECT @retrunDate = DATEADD(WEEK,@number-1,DATEADD(DAY,@day-DATEPART(DW,@start_date),@start_date))
ELSE
SELECT @retrunDate = DATEADD(WEEK,@number-2,DATEADD(DAY,@day-DATEPART(DW,@start_date),@start_date))
END
ELSE
BEGIN
IF(MONTH(DATEADD(WEEK,@number,DATEADD(DAY,@day-DATEPART(DW,@start_date),@start_date)))=@month_counter)
SELECT @retrunDate = DATEADD(WEEK,@number,DATEADD(DAY,@day-DATEPART(DW,@start_date),@start_date))
ELSE
SELECT @retrunDate = DATEADD(WEEK,@number-1,DATEADD(DAY,@day-DATEPART(DW,@start_date),@start_date))
END

INSERT INTO @ReturnTbl(Dates) SELECT (@retrunDate)

SET @month_counter = @month_counter + 1

END

RETURN;

END

No comments: