工作日:排除周日和法定节假日,根据自己业务需求进行调整,仅供参考
HolidayList 节假日表,保存各个节假日的开始 StartDate 和结束日期 EndDate
DECLARE @startDate DATE = ''
DECLARE @endDate DATE = ''
DECLARE @totalDays INT = DATEDIFF(DAY, @startDate, @endDate) +1
DECLARE @weekendDays INT = 0
DECLARE @holidayDays INT = 0
DECLARE @currentDate DATE = @startDate
WHILE @currentDate <= @endDate
BEGIN
DECLARE @holidayRange INT = (SELECT CASE WHEN StartDate <= @currentDate AND EndDate >= @currentDate THEN 1 ELSE 0 END FROM HolidayList WHERE StartDate <= @currentDate AND EndDate >= @currentDate)
IF @holidayRange = 1
BEGIN
SET @holidayDays += 1
END
IF DATEPART(WEEKDAY, @currentDate) = 1
BEGIN
SET @weekendDays += 1
END
SET @currentDate = DATEADD(DAY, 1, @currentDate)
END
DECLARE @workingDays INT = @totalDays - @weekendDays - @holidayDays
SELECT @totalDays AS TotalDays, @weekendDays AS WeekendDays, @holidayDays AS HolidayDays, @workingDays AS WorkingDays