I'm trying to write a T-SQL function that can find the third Tuesday, or the fourth Saturday, or the second Wednesday of every month. I found a VBScript version of something similar at VBScript and T-SQL don't do dates exactly the same way. I'm having a hard time wrapping my brain around how this is supposed to work. Here's my (non-working) function:
This code returns an error that says you can't use the modulo operator on datatype smalldatetime. You can in VBScript. To work around it, my first thought was to find out what day the Zeroeth Day of the Month (the last day of the previous month) was on using Datepart(day,@ZeroethDayOfMonth). This got me past the syntax error, but did not return the correct answers. The root of my problem is that I don't really grok the code I lifted from merlyn to begin with. Any insight would be greatly appreciated.
THANKS!
Code:
CREATE FUNCTION ufn_NthXday(@StartDate smalldatetime, @EndDate smalldatetime, @Nth tinyint, @XDay tinyint)
RETURNS @DayList TABLE (EventDate smalldatetime primary key)
AS
BEGIN
--Set up a @TempDate. Initialize it at @StartDate
DECLARE @TempDate smalldatetime
DECLARE @TempMonth tinyint
DECLARE @ZeroethDayOfMonth smalldatetime
SET @TempDate = @StartDate
WHILE @TempDate <= @EndDate
BEGIN
--Find out what month @TempDate is in and call it @TempMonth
SET @TempMonth = Datepart (month,@TempDate)
SET @ZeroethDayOfMonth = @TempDate - Datepart(day,@TempDate)
--Find the Nth Xday of @TempMonth. Make that the new @TempDate.
--From [URL unfurl="true"]http://www.merlyn.demon.co.uk/vb-dates.htm#ILS[/URL]
SET @TempDate = @ZeroethDayOfMonth + (7 * @Nth) - ((@ZeroethDayOfMonth - @Xday) % 7)
--Is @TempDate between @StartDate and @EndDate?
If @TempDate BETWEEN @StartDate AND @EndDate
--If so, keep it. Write it to @DayList.
BEGIN
INSERT INTO @DayList (EventDate)
VALUES (@TempDate)
END
--Go to the next month (add a month to @TempDate)
SET @TempDate = DATEADD ( month , 1, @TempDate )
END
RETURN
END
GO
This code returns an error that says you can't use the modulo operator on datatype smalldatetime. You can in VBScript. To work around it, my first thought was to find out what day the Zeroeth Day of the Month (the last day of the previous month) was on using Datepart(day,@ZeroethDayOfMonth). This got me past the syntax error, but did not return the correct answers. The root of my problem is that I don't really grok the code I lifted from merlyn to begin with. Any insight would be greatly appreciated.
THANKS!