The algorithm is as follows
If the day of week number is greater than the day of month number then this day must belong to a week in the prior month so calculate the DATEDIFF in weeks from the 1st Sunday of the prior month. Then Add 1 to make it the week #
ELSE calculate the DATEDIFF in weeks from the 1st Sunday of the current month . Then Add 1 to make it the week #
CREATE FUNCTION dbo.ufs_FirstofMonth (@theDate DATETIME)
RETURNS DATETIME
AS
BEGIN
RETURN ( DATEADD(d, (DAY(@theDate)-1) * (-1) ,@theDate ) )
END
GO
CREATE FUNCTION dbo.ufs_FirstSunday (@theDate DATETIME)
RETURNS DATETIME
AS
BEGIN
RETURN ( DATEADD(d, CASE WHEN DATEPART ( dw , dbo.ufs_FirstofMonth(@theDate)) = 1 THEN 0
ELSE 8-DATEPART ( dw , dbo.ufs_FirstofMonth(@theDate))
END
, dbo.ufs_FirstofMonth(@theDate)) )
END
GO
CREATE FUNCTION dbo.ufs_WeekOfMonth (@theDate DATETIME)
RETURNS INTEGER
AS
BEGIN
RETURN (CASE WHEN DATEPART ( dw , @theDate) > DAY(@theDate)
THEN 1 + DATEDIFF(wk, dbo.ufs_FirstSunday(DATEADD(mm,-1,@theDate)) , @theDate)
ELSE 1 + DATEDIFF(wk, dbo.ufs_FirstSunday(@theDate) , @theDate)
END
)
END
David Lundell
Principal Consultant and Trainer
www.mutuallybeneficial.com