0

我想知道是否有人在SQL中具有函數,而不是給定初始日期和星期幾(例如星期二),它可以計算自星期二開始日期起的下一個日期。給定日期的SQL函數根據星期幾參數計算下一個日期參數

例如:

考慮:

@ initialdate = 2013年1月2日 - 這一天是星期五

@dayofweek = 3 --3週三,1日和7週日

返回:日期= 2013年6月2日

也許我還沒有很好地解釋尚未.. 我的意思是 一個functi上,該參數@ DAYOFWEEK = 3(星期三),然後我可以給許多diferentes日期:

2013年1月2日,然後如果@ DAYOFWEEK = 3然後下一日期將是2013年6月2日

2013年2月2日,然後如果@ DAYOFWEEK = 3然後下一日期將是2013年6月2日

2013年3月2日,然後如果@ DAYOFWEEK = 3然後下一日期將是2013年6月2日

04-02-2013 then if @ dayofweek = 3 then next date will be 06-02-2013

05-02-2013 then if @ dayofweek = 3然後下一個日期將是2013年6月2日

2013年6月2日,然後如果@ DAYOFWEEK = 3然後下一日期將是13-02-2013

2013年7月2日,然後如果@ DAYOFWEEK = 3那麼下一次日期將是13-02-2013

+1

你能舉一些例子嗎?爲什麼'DateAdd(Day,1,myDate)'不適合你? –

+0

在Dateadd和'datename(dw,myDate)'之間返回星期幾的名字 - 這真的不是那麼難。 –

+0

@MichaelGardner我已經更新了這個問題.. – Artemination

回答

0

這很醜陋,但我試圖製作更優雅的解決方案並沒有那麼成功。

請注意,這假設DATEPART(dw,@someVarThatIsSunday)返回1.有關更多信息,請參閱Set DateFirst

declare @dayofweek int 
set @dayofweek = 3 
declare @initialDate datetime 
set @initialDate = getdate() 

declare @increment int 

select @increment = 
case DATEPART(dw, @initialDate) 
    when 1 then @dayofweek 
    when 2 then @dayofweek + 6 
    when 3 then @dayofweek + 5 
    when 4 then @dayofweek + 4 
    when 5 then @dayofweek + 3 
    when 6 then @dayofweek + 2 
    when 7 then @dayofweek + 1 
end 

if @increment > 7 
begin 
    set @increment = @increment - 7 
end 

select DATEADD(day, @increment, @initialDate) 
+0

非常感謝Dan – Artemination

+0

嗨,對於一種獨立於文化的方法,您可以檢查以下內容:stackoverflow.com/a/38601630/5089204。 – Shnugo