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/
Originally Posted on July 31, 2013
Last Updated on October 26, 2015
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.