Monday, October 25, 2010

Function to return all specific dates in a specific year

-- =============================================
-- Description: Function to return date for all month
-- Select * from dbo.GetDateOfAllMonth(1997,29)
-- =============================================
CREATE FUNCTION [dbo].[GetDateOfAllMonth]
(
@year INT, -- Year of Date
@number SMALLINT -- (n)th Date
)
RETURNS @ReturnTbl TABLE
(
Dates DATETIME
)
AS
BEGIN

DECLARE @start_date DATETIME, @end_date DATETIME, @retrunDate DATETIME, @total_days TINYINT,@counter TINYINT, @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)

SET @total_days = DAY(DATEADD(d, -DAY(DATEADD(m,1,CAST(CAST(YEAR(@start_date) AS VARCHAR(4)) + '-'
+ (CAST(MONTH(@start_date)AS VARCHAR(6)) + '-01') AS SMALLDATETIME))),DATEADD(m,1,CAST(CAST(YEAR(@start_date) AS VARCHAR(4)) + '-'
+ cast(MONTH(@start_date) AS VARCHAR(5)) + '-01' AS SMALLDATETIME))))

SET @end_date = CAST(CAST(@year AS VARCHAR(4)) + '-' + CAST(@month_counter AS VARCHAR(4)) + '-'+ CAST(@total_days AS VARCHAR(4)) As SmallDateTime)

SET @counter =1

WHILE @start_date <= @end_date
BEGIN

IF(DATEPART(dd , @start_date )= @number) AND @counter <= @number
BEGIN
--SELECT CAST(@start_date as VARCHAR(50)),DATEPART(dd , @start_date )
INSERT INTO @ReturnTbl(Dates) values (@start_date)
SET @counter = ISNULL(@counter,0)+1
END

SET @start_date = DATEADD(DAY,1,@start_date)
END

SET @month_counter = @month_counter + 1

END
--select * from @ReturnTbl
RETURN;

END

No comments: