如何在SQL Server中获得一个月的第二个星期四?
例如:
06/9/2016
07/14/2016
答案 0 :(得分:4)
这将在指定日期(@dtToday)开始获得星期四(@strDay)的第一,第二,第三等(@intIteration)。您可以将任何工作日传递到@strDay(例如“星期三”)。
TypeError: Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'.
像这样使用它:
ALTER FUNCTION [dbo].[GetDateOnNthDayOfMonth]
(
@intIteration int = null,
@strDay varchar(9) = null,
@dtToday datetime = null
)
RETURNS datetime
AS
BEGIN
DECLARE @dtReturn datetime = NULL
DECLARE @dtDate datetime
SET @strDay = ISNULL(@strDay, 'Monday')
SET @dtToday = ISNULL(@dtToday,GETDATE())
SET @dtDate = @dtToday
SET @intIteration = ISNULL(@intIteration,1) - 1
WHILE @dtReturn IS NULL
BEGIN
IF DATENAME(WEEKDAY, @dtDate) = @strDay
SET @dtReturn = DATEADD(DAY, @intIteration * 7, @dtDate)
ELSE
SET @dtDate = DATEADD(DAY, 1, @dtDate)
END
RETURN @dtReturn
END
答案 1 :(得分:2)
SELECT DATEADD(DAY, (DATEDIFF(DAY, 3,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) / 7) * 7 + 14, 3) AS NextDay
将GETDATE()替换为您想要的内容,它会在您提供的日期的第一天返回。
答案 2 :(得分:0)
简单创建一个函数并传递日期以获得所需的星期四日期
CREATE FUNCTION Get2nd_ThursDay(@CurrentDate DATETIME)
RETURNS DATETIME
AS
BEGIN
DECLARE @NextThursday DATETIME
SELECT @NextThursday = DATEADD(DAY, (DATEDIFF(DAY, 3,
DATEADD(MONTH, DATEDIFF(MONTH, 0, @CurrentDate), 0)) / 7) * 7 + 14, 3)
RETURN @NextThursday
END
然后在查询中使用
SELECT dbo.Get2nd_ThursDay(getdate())
答案 3 :(得分:-1)
您可以使用以下功能:
CREATE FUNCTION fn_DayOfMonth
(
@date datetime,
@day [int],
@num int
)
RETURNS datetime
AS
BEGIN
DECLARE @desiredDate as datetime;
DECLARE @firstDate as datetime;
SELECT @firstDate = DATEADD(month, DATEDIFF(month, 0, @date), 0);
SELECT @desiredDate = DATEADD(DAY, ( ( (7 * @num + @day) - DATEPART(dw, @firstDate) ) % 7 ) + 7, @firstDate);
RETURN @desiredDate;
END
GO
并按如下方式使用:
SELECT [dbo].[fn_DayOfMonth]('2016-06-09', 5, 2)
第一个参数是输入日期,第二个参数是星期几(1表示星期日,7表示星期六),最后一个参数是发生日期。