1

我有一个存储函数,它应该计算出我的工资单周开始日期。哪个是“星期四” 但是我的存储过程总是将我的开始日期设为“星期五” 我的声明和设置函数有什么问题?我希望我的 StartWeekDay 为“Thursday”...“lStartday”在帐户表中设置为“5”我的代码如下:

DECLARE @StartWeekDay int 
SET @StartWeekDay = (Select lStartDay From Account Where lLocationID = 1)

DECLARE @CurrentDate DateTime 
SET @CurrentDate = GetDate()
DECLARE @CurrentWeekDay int
SET @CurrentWeekDay = DATEPART(dw,@CurrentDate)

DECLARE @Diff int
SET @Diff = @StartWeekDay - @CurrentWeekDay

SET @Diff = Case When @Diff > 0 Then -6 When @Diff = 0 Then 0 Else @Diff End

--
 DECLARE @DaysToStart int
 SET @DaysToStart = (DatePart(dw,@CurrentDate) - @StartWeekDay)
 IF @DaysToStart <= .1 
  BEGIN
    SET @DaysToStart = @DaysToStart + 7 
  END

 DECLARE @myStartWeekDate DateTime
 --SET @myStartWeekDate = dbo.DateOnly(DATEADD(d,@Diff,@CurrentDate))
 SET @myStartWeekDate =  Convert(nvarchar,DateAdd(d,-@DaysToStart,@CurrentDate),101) -- getting DATE only
--
4

3 回答 3

4

以下查询是将日期四舍五入到一周开始的标准方法。然而,这被视为星期一......

DATEADD(WEEK, DATEDIFF(WEEK, 0, @YourDate), 0)

如果您将值偏移 3,这会将函数更改为向下舍入到上一个星期四...

DATEADD(WEEK, DATEDIFF(WEEK, 0, @YourDate-3), 3)

编辑:这应该是 3,而不是 4...

SET @yourDate    = getDate()
SET @firstDay    = 3
SET @RoundedDate = DATEADD(WEEK, DATEDIFF(WEEK, 0, @YourDate-@firstDay), @firstDay)

 Value of @firstDay | Day of week this will round to
--------------------+--------------------------------
        0           |        Monday
        1           |        Tuesday
        2           |        Wednesday
        3           |        Thursday
        4           |        Friday
        5           |        Saturday
        6           |        Sunday
于 2012-08-16T13:22:40.467 回答
1

lStartDay = 5 总是会给你星期五。您需要为星期四添加 4

DECLARE @DaysToStart int
 SET @DaysToStart = (DatePart(dw,@CurrentDate) - @StartWeekDay)
 IF @DaysToStart <= .1 
  BEGIN
    SET @DaysToStart = @DaysToStart + 7 
  END

如果您声明 @DaysToStart 并且 DatePart 也返回 INT,为什么要与 .1 进行比较?

于 2012-08-16T13:12:48.277 回答
0
        DECLARE @StartWeekDay int 
    SET @StartWeekDay = 5

    DECLARE @CurrentDate DateTime 
    SET @CurrentDate = '8/24/2012'
    DECLARE @CurrentWeekDay int
    SET @CurrentWeekDay = DATEPART(dw,@CurrentDate)
    SELECT @CurrentWeekDay;

    DECLARE @Diff int
    SET @Diff = @StartWeekDay - @CurrentWeekDay

    SET @Diff = Case When @Diff > 0 Then -6 When @Diff = 0 Then 0 Else @Diff End

    --
     DECLARE @DaysToStart int
     SET @DaysToStart = (DatePart(dw,@CurrentDate) - @StartWeekDay)
--change here to <1 and not <=1 that will add 8 and return friday at the end
     IF @DaysToStart < 1 
      BEGIN
        SET @DaysToStart = @DaysToStart + 7 
      END
      SELECT @DaysToStart;
     DECLARE @myStartWeekDate DateTime
     --SET @myStartWeekDate = dbo.DateOnly(DATEADD(d,@Diff,@CurrentDate))
     SET @myStartWeekDate =  Convert(nvarchar,DateAdd(d,-@DaysToStart,@CurrentDate),101) 
     SELECT @myStartWeekDate
于 2012-08-16T13:23:04.333 回答