sknox (8/21/2009)
Why not just do (using the function definition and parameters (and the @firstDate variable) as given):
set @firstDate = dateadd(dd,1-datepart(dd,@inputdate) ,@inputDate) -- ensures that we start with the first of the month
select
dateadd(wk, @occurAt - 1, -- adds the additional weeks, if any
dateadd(dd, @day - datepart(dw, @firstDate)-- moves to the given day of week
+ case when @day < datepart(dw, dateadd(dd,1-datepart(dd,@firstdate) ,@firstDate)) then 7 else 0 end, -- ensures we don't go back to the last month
@firstDate
)
)
I agree... the only desireable thing missing from the above code is for the "LAST" desired occurance. For example... for 2012-02-01 looking for Sunday(1) as the last occurance of a Sunday in the month (5), your good code returns the first Sunday of March instead of the last Sunday of February.
--Jeff Moden
Change is inevitable... Change for the better is not.