我需要返回所有日期都在用户输入日期之前的指定时间内的记录(最有可能是一周但它可以是任何东西),我试过这个,但它似乎不起作用:
where T.postdate >= DateADD(day, @Length, @StartDate)
其中@Length和@StartDate是由用户在存储过程中输入的,但它的返回日期是从几个月前开始的。
答案 0 :(得分:0)
如果我理解正确,你可以这样做:
http://sqlfiddle.com/#!6/7241b/4
create table test (someDate datetime)
insert into test (someDate)
select '2014-01-01'
union all select '2014-02-01'
union all select '2014-03-01'
union all select '2014-04-01'
union all select '2014-05-01'
union all select '2014-06-01'
union all select '2014-07-01'
union all select '2014-08-01'
union all select '2014-09-01'
union all select '2014-10-01'
union all select '2014-10-02'
union all select '2014-10-03'
union all select '2014-10-04'
union all select '2014-10-05'
union all select '2014-10-06'
union all select '2014-10-07'
union all select '2014-10-08'
union all select '2014-10-09'
union all select '2014-10-10'
union all select '2014-10-11'
declare @lengthInDays int, @startDate datetime
select @lengthInDays=5, @startDate='2014-10-02'
select *
from test
-- where "somedate" is after the start date minus the number of days input
where someDate >= dateadd(day, -@lengthInDays, @startDate)
-- and where the "someDate" is not greater than the date input
and someDate < @startDate
此实例中仅返回结果为2010-10-01
,因为它位于@startDate和@startDate之前5天
答案 1 :(得分:0)
Try this.
WHERE T.postdate >= DATEADD(week, -@Length, @StartDate)