我只能选择访问数据库,并且无法创建存储过程。当where子句一次过滤一个数据时,有关如何自动查询日期范围的任何想法吗?
例如....我需要为2013年4月1日至2013年4月30日之间的每个日期运行一个类似于下面的查询。看起来我应该可以用光标或其他东西来做这件事。
declare @AsOfDate datetime
SET @AsOfDate = '4/1/2013'
select *,@AsOfDate AS 'AsOfDate' from table p
where
p.ENTER_WQ_DT <= @AsOfDate and
((coalesce(p.FILE_DATE,p.DELETE_DATE) > @AsOfDate ) or (p.FILE_DATE is null and p.DELETE_DATE is null and WQ_CTE.TAR_ID is not null))
我希望能够运行它并生成包含所有记录的结果,就像我手动编辑AsOfDate变量并在每月的每一天运行它一样。
答案 0 :(得分:2)
declare @AsOfDateStart datetime, @AsOfDateEnd datetime;
select @AsOfDateStart = '20130401', @AsOfDateEnd = '20130430';
-- this "WITH" block starts a recursive Common Table Expression (CTE)
-- that makes up a "table" of the dates, one per row
with Dates as (
select @AsOfDateStart AsOfDate
union all
select dateadd(d,1,AsOfDate)
from Dates
where AsOfDate < @AsOfDateEnd
)
select p.*, d.AsOfDate
from Dates d
join tablep p
on p.ENTER_WQ_DT <= d.AsOfDate and
((coalesce(p.FILE_DATE,p.DELETE_DATE) > d.AsOfDate ) or (p.FILE_DATE is null and p.DELETE_DATE is null and WQ_CTE.TAR_ID is not null));
关于此查询:
有关您的查询的说明:
答案 1 :(得分:1)
SQL Server提供looping mechanisms.
类似的东西:
declare @AsOfDate datetime = '2013-04-01'
declare @EndDate datetime = '2013-05-01'
WHILE (@AsOfDate < @EndDate) BEGIN
--your query here
SET @AsOfDate = DATEADD(day, 1, @AsOfDate)
END