将日期移至最近的星期日,并在星期一结束

时间:2014-03-29 16:49:36

标签: sql-server

我想写一个商店程序,我通过了两个日期范围,它显示了Order table范围之间的数据,但我希望我的输出日期范围移动到最近的Sunday和在Saturday结束。即如果我将27-Mar-2014的起始日期= Thursday传递给它,它会显示日期23-Mar-2014的数据Sunday,以及何时我通过第二个日期,即我通过4-Apr-2014,然后它的结束范围变为7-Apr-2014,这是星期一。简而言之,无论我通过日期范围,它都会将开始日期设为该周的Sunday该周的结束日期Monday。谢谢

create procedure getdata 
@StartDate as Datetime, 
@EndDate as Datetime 
as 
begin 
select * from Table_8 
where Table_8.Date >= @StartDate 
and Table_8.Date   <= @EndDate 
order by Table_8.[Date] 
end  

declare @StartDate_temp as datetime  
declare @EndDate_temp as datetime  
set @StartDate_temp = DATEADD(dd, -(DATEPART(dw, '2013-01-05')-1), '2013-01-05') 
set @EndDate_temp   = DATEADD(dd, 7-(DATEPART(dw, '2013-01-13')), '2013-01-13') 
exec getdata @StartDate_temp,@EndDate_temp

2 个答案:

答案 0 :(得分:0)

简单的解决方案是使用weekday,但这又取决于DateFirst的规范。为了隔离这种依赖(并且可能引入语言依赖),以下使用case

select blah
from foo
where OrderDate >= dateadd(day, (case datename(weekday, @StartDate)
                                   when 'Sunday' then 0
                                   when 'Monday' then 1
                                   when 'Tuesday' then 2
                                   when 'Wednesday' then 3
                                   when 'Thursday' then 4
                                   when 'Friday' then 5
                                   when 'Saturday' then 6
                                 end)
                          @StartDate
                   ) and
       OrderDate <= dateadd(day, (case datename(weekday, @EndDate)
                                   when 'Sunday' then 6
                                   when 'Monday' then 5
                                   when 'Tuesday' then 4
                                   when 'Wednesday' then 3
                                   when 'Thursday' then 2
                                   when 'Friday' then 1
                                   when 'Saturday' then 0
                                 end),
                            @EndDate)
                   )

答案 1 :(得分:0)

您可以从第一个参数获取周开始日期,从第二个参数获取周末日期,并将这些参数传递给您的过程中的选择查询。像这样......

CREATE PROCEDURE usp_MyProc
 @Date_Param_1 VARCHAR(20),
 @Date_Param_2 VARCHAR(20)
AS
BEGIN
  SET NOCOUNT ON;

 DECLARE @DateTime1 DATETIME, @DateTime2 DATETIME
       , @StartDate DATETIME, @EndDate DATETIME;

  SET @DateTime1 = CAST(@Date_Param_1 AS DATETIME)
  SET @DateTime2 = CAST(@Date_Param_2 AS DATETIME)

  SET @StartDate =  DATEADD(dd, -(DATEPART(dw, @DateTime1)-1), @DateTime1) 

  SET @EndDate   = DATEADD(dd, 7-(DATEPART(dw, @DateTime2)), @DateTime2) 

-- Now your Rest of the query 

 SELECT *
 FROM [Order]
 WHERE OrderDate >= @StartDate
  AND  OrderDate <= @EndDate

END