CREATE FUNCTION fnBusinessDays ( @StartDate DATETIME ,@EndDate DATETIME ) RETURNS INT AS BEGIN IF ( @StartDate IS NULL OR @EndDate IS NULL ) RETURN (0) DECLARE @i INT = 0; WHILE (@StartDate <= @EndDate) BEGIN SET @i = @i + CASE WHEN datepart(dw, @StartDate) BETWEEN 2 AND 6 THEN 1 ELSE 0 END SET @StartDate = @StartDate + 1 END -- while RETURN (@i) END -- function GO SELECT dbo.fnBusinessDays('2016-01-01', '2016-12-31')
Source: http://www.sqlusa.com/bestpractices/datetimeconversion/
Last Updated on October 26, 2015