Count work days between two dates

前端 未结 24 2693
失恋的感觉
失恋的感觉 2020-11-22 01:05

How can I calculate the number of work days between two dates in SQL Server?

Monday to Friday and it must be T-SQL.

24条回答
  •  醉话见心
    2020-11-22 01:50

    If you need to add work days to a given date, you can create a function that depends on a calendar table, described below:

    CREATE TABLE Calendar
    (
      dt SMALLDATETIME PRIMARY KEY, 
      IsWorkDay BIT
    );
    
    --fill the rows with normal days, weekends and holidays.
    
    
    create function AddWorkingDays (@initialDate smalldatetime, @numberOfDays int)
        returns smalldatetime as 
    
        begin
            declare @result smalldatetime
            set @result = 
            (
                select t.dt from
                (
                    select dt, ROW_NUMBER() over (order by dt) as daysAhead from calendar 
                    where dt > @initialDate
                    and IsWorkDay = 1
                    ) t
                where t.daysAhead = @numberOfDays
            )
    
            return @result
        end
    

提交回复
热议问题