I am trying to construct an sql query using a while loop that increments a datetime by one minute each iteration and then generates a select statement based on the time:
declare @dt datetime
set @dt = '2011-7-21'
while @dt < '2011-7-22'
begin
select Count(*) From Actions Where Timestamp = @dt
set @dt = DATEADD(mi, 1, @dt)
end
The query works as intended except that every iteration of the while loop seems to produce a new query entirely, rather than simply a new row. Is there a way to construct this so that its one single query and each row is generated by the incrementation of the loop? I believe this occurs because the select statement is inside the loop, but I'm not sure how to construct it a different way that works.
EDIT - Here is what I came up with using a temporary table, but it is slow. Maybe there is a faster way? If not thats fine, atleast this works:
create table #temp
(
[DT] datetime not null,
[Total] int not null
)
declare @dt datetime
declare @result int
set @dt = '2011-7-21'
while @dt < '2011-7-22'
begin
set @result = Count(*) From Actions Where Timestamp = @dt
insert #temp ([DT],[Total]) values (@dt, @result)
set @dt = DATEADD(mi, 1, @dt)
end
select * from #temp;
drop table #temp;
set @dt = '2011-7-21' ... Where Timestamp = @dt