3

我正在使用带有 t-Sql 的 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

该代码似乎有效。想知道我是否遗漏了什么,或者是否有更好的方法来处理这个问题。

4

4 回答 4

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
于 2012-08-02T14:48:33.990 回答
0

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

我可能有的唯一建议是您需要整合假日支票吗?我们有一个 Holiday 表来存储也需要跳过的日期。

于 2012-08-02T14:46:57.333 回答
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
于 2013-10-04T07:55:08.183 回答
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
于 2013-10-04T10:53:50.343 回答