我有一个存储函数,它应该计算我的工资单的周开始日期。哪个是“星期四”但是我的存储过程总是让我的开始日期为“星期五”我的声明和设置功能有什么问题?我希望我的StartWeekDay为“星期四”...帐户表中“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
--
答案 0 :(得分: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
答案 1 :(得分: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进行比较
答案 2 :(得分: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