0

在 SQL Server 2008 中,给定一个日期,我将如何获得对应于该周 FRI 的日期?

so for example:
6/6/2012 -> 6/8/2012
6/5/2012 -> 6/8/2012
4

2 回答 2

2

假设您希望 2012 年 6 月 9 日也返回 2012 年 6 月 8 日(同一周),这将起作用。它获取当前日期的星期几,并将该日期与星期五之间的差值硬编码为 6。

SET DATEFIRST 7;    
declare @date date = '6/5/2012'

select dateadd(dd,6-datepart(dw,@date),@date) as Friday

如果你想让 6/9/2012 下周五返回,你只需要做一个小的修改:

SET DATEFIRST 7;
declare @date date = '6/9/2012'
set @date = dateadd(dd,1,@date) -- this adds a day to the date you inputted but doesn't matter since the function will always return to you a Friday
-- Sunday resets the week with datepart so adding a day to Saturday resets the week resulting in the next week being returned.

select dateadd(dd,6-datepart(dw,@date),@date) as Friday
于 2012-06-06T20:32:41.863 回答
1

这是我创建的一个似乎有效的函数。它不会更改 DATEFIRST,并且会为您提供 DOW 的下一个日期。如果它在您正在寻找的 DOW 上,该函数将返回您传入的日期。

CREATE FUNCTION [dbo].[func_NextDate]
(
    @dt DATE,
    @dow INT -- Use the day-of-week as defined by SQL Server (1=Sun, 7=Sat)
)
RETURNS DATE
AS 
BEGIN

DECLARE @dtDiff INT = 7-((DATEPART(dw, @dt)+(7-@dow))%7)
IF @dtDiff = 7
    SET @dtDiff = 0 -- Return the date if it is on the dow requested

RETURN DATEADD(dd, @dtDiff, @dt)

END
于 2015-10-28T00:11:13.710 回答