在SQL Server 2008中,给定一个日期,我如何获得与该周的FRI相对应的日期?
so for example:
6/6/2012 -> 6/8/2012
6/5/2012 -> 6/8/2012
答案 0 :(得分:2)
假设您希望6/9/2012也返回6/8/2012(同一周),这将有效。 它获取当前日期的星期几,并将其与星期五之间的差异加上硬编码为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
答案 1 :(得分: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