如何查找给定日期名称

时间:2016-05-18 18:11:08

标签: sql sql-server-2012 sql-function

我正在尝试在SQL中编写一个函数来返回给定日期名称的最近或下一个日期。

例如,今天是2016年5月18日星期三,我想通过函数day ='Mon'period ='next'并返回23/5/16或者day ='Mon'period ='last'返回16/05/16。

我尝试了以下但是看起来太笨重了,因为我仍然需要为最近的日期和下周的日期添加逻辑。

有人能指出我如何最好地接近这个方向吗?

提前致谢。

DECLARE @theWeekday VARCHAR(3) = 'Sun';
DECLARE @dayDiff INT;
DECLARE @dayOfWeek TINYINT
DECLARE @todayOfWeek TINYINT

--return thursday last week select DATEADD(DAY, ((DATEDIFF(DAY, '19000104', getdate()) / 7) * 7) hence why i have @dayOfWeekThu
DECLARE @dayOfWeekThu INT = 4;

SET @dayOfWeek = CASE @theWeekday
         WHEN 'Mon' THEN 1
         WHEN 'Tue' THEN 2
         WHEN 'Wed' THEN 3
         WHEN 'Thu' THEN 4
         WHEN 'Fri' THEN 5
         WHEN 'Sat' THEN 6
         WHEN 'Sun' THEN 7
END


If @dayOfWeekThu < @dayOfWeek
BEGIN
    SET @dayDiff = @dayOfWeekThu-@dayOfWeek;
END
ELSE
BEGIN
    SET @dayDiff = ABS(@dayOfWeek-@dayOfWeekThu);
END

select DATEADD(DAY, ((DATEDIFF(DAY, '19000104', getdate()) / 7) * 7) - @dayDiff, '19000104')

1 个答案:

答案 0 :(得分:0)

我的想法是得到当周第一天的日期,之后就相当简单了。

declare @wk int  
       ,@yr int 
       ,@Date datetime
       ,@dayOfWeek int
       ,@theWeekday VARCHAR(3) = 'fri'
       ,@Period varchar(10) ='Next'


   set @yr = year(getdate())
   set @wk = DATEPART( wk, getdate())-1
   set @Date =  dateadd (week, @wk, dateadd (year, @yr-1900, 0)) - 4 -
         datepart(dw, dateadd (week, @wk, dateadd (year, @yr-1900, 0)) - 4) +2

SET @dayOfWeek = CASE @theWeekday
         WHEN 'Mon' THEN 0
         WHEN 'Tue' THEN 1
         WHEN 'Wed' THEN 2
         WHEN 'Thu' THEN 3
         WHEN 'Fri' THEN 4
         WHEN 'Sat' THEN 5
         WHEN 'Sun' THEN 6
         end


if @Period = 'Next'
begin

set @Date = dateadd("dd",@dayOfWeek,dateadd(wk, 1, @Date))
end

else 

begin
set @Date = dateadd("dd",@dayOfWeek,dateadd(wk, 0, @Date))
end

select @Date