Sql Server Function to get number of working days in given days.

Here is an example to get the number of working days in given couple of days.

CREATE FUNCTION dbo.GetWorkingDays
(
@startDate SMALLDATETIME,
@endDate SMALLDATETIME
)
RETURNS INT
AS
BEGIN
DECLARE @WDays INT;
SET @WDays = DATEDIFF(DAY, @startDate, @endDate)+1;
RETURN
(
SELECT @WDays / 7 * 5 + @WDays % 7 -
(
SELECT COUNT(*) FROM
(
SELECT 1 AS d
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4
UNION ALL SELECT 5
UNION ALL SELECT 6
UNION ALL SELECT
) weekdays
WHERE d <= @WDays % 7
AND DATENAME(WEEKDAY, @endDate - d + 1)
IN
(
'Saturday',
'Sunday'
)
)
);
END
GO
PRINT dbo.getWorkingDays('20080601', '20080630')


...S.VinothkumaR.

No comments: