Skip to content

Instantly share code, notes, and snippets.

@fesenpav
Created October 20, 2022 15:49
Show Gist options
  • Save fesenpav/dbec8ef875c25771c819b90fa34bcbef to your computer and use it in GitHub Desktop.
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).
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