首先,我认为您可能希望在 where 子句中使用 DateDiff 函数,而不是计算所需的截止日期并在 where 子句中的日期列上使用任何计算,这将更有效,所以而不是
WHERE DATEDIFF(day, date, getdate() ) <= #url.d#
你会有类似的东西
WHERE date >= @cutoffDate
其中@cutoffDate 是基于#url.d# 的计算日期
现在,至于抓住正确的截止日期。我的假设是,在正常情况下,请求会返回文章,否则您将只获取最近日期的文章。因此,我将采取的方法是获取计算截止日期的最旧日期(基于#url.d# 和最近的文章日期。类似的东西
-- @urld == #url.d
-- compute the cutoff date as the OLDEST of the most recent article and
-- the date based on #url.d
declare @cutoff datetime
select @cutoff = DateAdd(dd,-1*@urld,GetDate())
select @cutoff
select @cutoff = min(cutoffDate)
from
(SELECT Max(date) as cutoffDate from News
UNION
select @cutoff) Cutoff
-- grab the articles with dates that are more recent than the cutoff date
select *
from News
WHERE date >= @cutoff
我还猜想您可能希望将日期四舍五入到午夜(我在这里没有这样做)。这是一种多查询方法,可能应该在单个存储过程中实现......如果这是您正在寻找的。
祝项目顺利!