Well here is one way to do it although I'm not certain you will be able to compile this as a UDF. I couldn't try it because (here at home) I only have 2000. So I couldn't even try the code outside the function but unless I have a typo it should work.>>it is not clear, at least to me, how to use such calendar to find the Xth weekday of the monthThis approach is using a table in the master database as a "numbers" table. I'm returning the numbers 0-31 and using that number in a DATEADD function to generate all the dates that could be in your month. Then limiting those days to whatever day of the week you want. Included is a ranking function: ROW_NUMBER() which will allow us to limit the results to the 2nd, 3rd, whatever occurance.declare @dtStart datetime ,@dayOfWeek int ,@dowOccurance intselect @dtStart = '2008-05-01' --May 2005 ,@dayOfWeek = 3 --Tuesday ,@dowOccurance = 3 --3rd occuranceselect dtfrom ( select dateadd(day, number, @dtStart) dt ,row_number() over (order by number) rn from master..spt_values where type = 'p' and number < 32 and datepart(weekday, dateadd(day, number, @dtStart)) = @dayOfWeek --only our weekdays of interest and datediff(month, @dtStart, dateadd(day, number, @dtStart)) = 0 --make sure it's the same month ) dwhere d.rn = @dowOccurance
Be One with the OptimizerTG