Created
May 20, 2020 16:32
-
-
Save vpetkovic/1b7f72095a20c007948982fb18950f5c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE FUNCTION dbo.fnGetNthWeekdayOfMonth | |
( | |
@theDate DATETIME, | |
@theWeekday TINYINT, | |
@theNth SMALLINT | |
) | |
RETURNS DATETIME | |
BEGIN | |
RETURN ( | |
SELECT theDate | |
FROM ( | |
SELECT DATEADD(DAY, 7 * @theNth - 7 * SIGN(SIGN(@theNth) + 1) +(@theWeekday + 6 - DATEDIFF(DAY, '17530101', DATEADD(MONTH, DATEDIFF(MONTH, @theNth, @theDate), '19000101')) % 7) % 7, DATEADD(MONTH, DATEDIFF(MONTH, @theNth, @theDate), '19000101')) AS theDate | |
WHERE @theWeekday BETWEEN 1 AND 7 | |
AND @theNth IN (-5, -4, -3, -2, -1, 1, 2, 3, 4, 5) | |
) AS d | |
WHERE DATEDIFF(MONTH, theDate, @theDate) = 0 | |
) | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment