Created
October 20, 2022 15:49
-
-
Save fesenpav/dbec8ef875c25771c819b90fa34bcbef to your computer and use it in GitHub Desktop.
SQL Function that returns working day of month by index (returns only day number).
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 WORKING_DAY_OF_MONTH | |
( | |
@DayIndex INT, -- Searched day index | |
@Month INT, -- Month | |
@Year INT -- Year | |
) | |
RETURNS INT AS | |
BEGIN | |
DECLARE @Index INT = 1 | |
DECLARE @DaysFound INT = 0 | |
WHILE (@DaysFound != @DayIndex) | |
BEGIN | |
IF(ISDATE(CONCAT(@Year, '-', @Month, '-', @Index)) = 0) | |
BEGIN | |
RETURN @Index-1 | |
END | |
IF(DATEPART(WEEKDAY, DATEFROMPARTS(@Year, @Month, @Index)) IN (1,2,3,4,5)) | |
BEGIN | |
SET @DaysFound = @DaysFound + 1 | |
END | |
SET @Index = @Index + 1 | |
END | |
RETURN @Index | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment