2012-08-02 47 views
3

我正在使用t-sql的SQL Server 我有以下代码,检查日期是否落在周末 ,如果if它会重复,直到一天工作日为止SQL Server检查一天是否不会在周末,如果是这样,迭代到一个工作日

Declare @ProDate as Date 
    set @ProDate = '08/05/12' 

    WHILE (DATEPART(DW, @ProDate) = 1 OR DATEPART(DW, @ProDate) = 7) 
    BEGIN 

     set @ProDate = DATEADD(day, 1, @ProDate) 

    END 

    select @ProDate 

该代码似乎工作。想知道我是否遗漏了任何东西,或者是否有更好的方法来处理这个问题。

回答

0

此代码将工作。它与我们在大量使用的函数中使用的代码几乎相同。

唯一的建议可能是你需要整合假期检查吗?我们有一张假期表来存储需要跳过的日期。

+0

它不需要跳过假期。感谢您的反馈意见! – 2012-08-02 14:47:49

+1

@NatePet你唯一需要验证的是你的系统中的'dateFirst',然后你可能需要从那里进行调整。我们的代码使用'((@@ dateFirst + DatePart(dw,@ ProDate)-2)%7)+ 1'来确定星期几。 – Taryn 2012-08-02 14:51:44

3

此代码依赖于系统中的DATEFIRST的设置。

我想补充的日期检查

或者前SET DATEFIRST 7,这避免了while循环下面的代码

declare @df int = @@Datefirst  
set datefirst 1  
select 
    case when DATEPART(DW, @ProDate)>=6 then 
     DATEADD(d, 8-DATEPART(DW, @ProDate), @prodate) 
    else @ProDate 
    end  
set DATEFIRST @df 
0

使用不包括周末和节假日

Declare @AddDay as integer = 3 
Declare @NextWorkingDate DateTime 
Declare @StartDate DateTime = Cast(getdate() as date) 

While @AddDay > 0 
    begin 

     Select @NextWorkingDate = @StartDate + @AddDay + 
     (datediff(wk, @StartDate, @StartDate+ @AddDay ) * 2) -- add weekend 

     --Exclude weekend 
     If datepart(dw,@NextWorkingDate) = 1 or datepart(dw,@NextWorkingDate) = 7 --Add 2 days if target date is either Saturday or Sunday 
      set @NextWorkingDate = @NextWorkingDate + 2 

     --Count no of holidays if falling within start date and nextwrking date 
     Select @AddDay = Count(*) from HolidayTable ST --Holiday list 
        where ST.OffDate between @StartDate+1 and @NextWorkingDate 
     Set @StartDate = @NextWorkingDate 
    End   

Select @NextWorkingDate 
后获得下一wrking日期
0

以下使用排除周末假日

Declare @AddDay as integer = 3 
Declare @NextWorkingDate DateTime 
Declare @StartDate DateTime = Cast(getdate() as date) 

While @AddDay > 0 
    begin 

     Select @NextWorkingDate = @StartDate + @AddDay + 
     (datediff(wk, @StartDate, @StartDate+ @AddDay ) * 2) -- add weekend 

     --Exclude weekend 
     If datepart(dw,@NextWorkingDate) = 1 or datepart(dw,@NextWorkingDate) = 7 --Add 2 days if target date is either Saturday or Sunday 
      set @NextWorkingDate = @NextWorkingDate + 2 

     --Count no of holidays if falling within Hold days/Deposit days 
     Select @AddDay = Count(*) from HolidayTable ST --Holiday list 
        where ST.OffDate between @StartDate+1 and @NextWorkingDate 
     Set @StartDate = @NextWorkingDate 
    End   

Select @NextWorkingDate 
相关问题