Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I would like to write a function that returns, for example, the first wednesday of every month between @d1 and @d2 where @d1 and @d2 are smalldatetimesCREATE FUNCTION dbo.udf_XDayInYWeekBetweenDateXAndDateY (@DateX smalldatetime, @DateY smalldatetime, @Wk int, @DoW int)RETURNS @Dates TABLE (@date smalldatetime)SELECT * FROM dbo.udf_XDayInYWeekBetweenDateXAndDateY ('2006-01-01', '2006-03-01', 1, 4)would return'2006-01-04 00:00:00''2006-02-01 00:00:00'I'm currently working on a solution myself, but I thought if anyone had anything already done I could already have it done.
nosepicker
Constraint Violating Yak Guru
366 Posts
Posted - 2005-12-05 : 14:18:56
Without writing the logic to handle the dates between @d1 and @d2, here is a single statement to calculate the first Wednesday of a month, given the 1st of the month:DECLARE @date datetimeSET @date = CONVERT(datetime, '2006-01-01')SELECT DATEADD(wk, DATEDIFF(wk, 2, CASE WHEN DATEPART(dw, @date) IN (5, 6, 7) THEN DATEADD(w, 1, @date) ELSE @date END), 2)
djseng
Starting Member
25 Posts
Posted - 2005-12-05 : 14:51:26
Thank you much sir,You saved me an undetermined amount of hours of work!
DECLARE @date smalldatetime, @wom int, @dow intSELECT @date = '2006-04-01 00:00:00', @wom = 1, -- Week Of Month @dow = 7 -- Day Of WeekSELECT DATEADD( wk, DATEDIFF( wk, @dow - 2, CASE WHEN DATEPART(dw, @date) BETWEEN @dow + 1 AND 7 THEN DATEADD(wk, @wom, @date) ELSE DATEADD(wk, @wom - 1, @date) END), @dow - 2)