我不是 SQL Server 方面的专家,但这应该会让你很接近。把它放在一个 SQL 函数中:
DECLARE @date DATETIME = '10/03/2013';
SELECT MIN(Date) AS NextFridayOrEoMonth
FROM ( SELECT DATEADD(DAY, ( CASE DATEPART(DW, @date)
WHEN 7 THEN 6
ELSE 6 - DATEPART(DW, @date)
END ), @date) AS Date
UNION
SELECT DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, @date) + 1, 0)) AS Date
) AS dates;
编辑: 实际上,这里是一个函数。祝你好运!
CREATE FUNCTION dbo.NextFridayOrEoMonth ( @date DATETIME )
RETURNS DATETIME
WITH SCHEMABINDING,
RETURNS NULL ON NULL INPUT
AS
BEGIN
DECLARE @result DATETIME;
SELECT @result = MIN(Date)
FROM ( SELECT DATEADD(DAY, ( CASE DATEPART(DW, @date)
WHEN 7 THEN 6
ELSE 6 - DATEPART(DW, @date)
END ), @date) AS Date
UNION
SELECT DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, @date) + 1, 0)) AS Date
) AS dates;
RETURN @result;
END
GO
SELECT dbo.NextFridayOrEoMonth('10/3/2013') AS NextFridayOrEoMonth; -- 2013-10-04
SELECT dbo.NextFridayOrEoMonth('10/5/2013') AS NextFridayOrEoMonth; -- 2013-10-11
SELECT dbo.NextFridayOrEoMonth('10/14/2013') AS NextFridayOrEoMonth; -- 2013-10-18
SELECT dbo.NextFridayOrEoMonth('10/25/2013') AS NextFridayOrEoMonth; -- 2013-10-25
SELECT dbo.NextFridayOrEoMonth('10/26/2013') AS NextFridayOrEoMonth; -- 2013-10-31
SELECT dbo.NextFridayOrEoMonth('10/29/2013') AS NextFridayOrEoMonth; -- 2013-10-31
GO
注意: 代码审查/评论表示赞赏。