Skip Weekends SQL Function

Certain reports need to show data that excludes data from weekends. There is a couple of ways to approach this. You could create a Calendar table, but sometimes you do not need to go that far when a simple query would suffice. The following function makes use of the DateAdd SQL function to add 1 to the current date if it is a Sunday, or 2 when it is a Saturday:

CREATE FUNCTION NoWeekends(@AddToDate AS DATE, @NumberOfDays AS INT)RETURNS DATETIMEASBEGIN    SET @AddToDate = DATEADD(d, @NumberOfDays, @AddToDate)    IF DATENAME(DW, @AddToDate) = 'sunday'   SET @AddToDate = DATEADD(d, 1, @AddToDate)    IF DATENAME(DW, @AddToDate) = 'saturday' SET @AddToDate = DATEADD(d, 2, @AddToDate)      RETURN CAST(@AddToDate AS DATETIME)ENDGOSELECT dbo.NoWeekends(GETDATE(), 3) 
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

More From DevX