我想在sql中循环或类似方法以下代码

时间:2010-12-27 03:57:14

标签: sql-server sql-server-2005 stored-procedures

这是我的代码。

declare @dt datetime;
declare @AddTime int;
declare @earliestTime int;
declare @latestTime int;
declare @basedTime int;

set @dt = cast('01-01-1980 00:00:00' as datetime)
select @earliestTime = min(DATEDIFF(MINUTE, @dt, starttime)) from visit
select @latestTime = max(DATEDIFF(MINUTE, @dt, starttime)) from visit
set @AddTime = 30;
set @basedTime = @earliestTime;
set @earliestTime = @earliestTime + @AddTime;

SELECT
    count(DATEDIFF(MINUTE, @dt, starttime)) as 'Ticket Issued',
    @earliestTime as 'Period',
    count(DATEDIFF(MINUTE, @dt, nexttime)) as 'Called Tickets',
    SUM(case when DATEDIFF(second, starttime, nexttime) <= 900 then 1 else 0 end)
        as 'Less than Accepted Waiting Time'
    from visit
    where DATEDIFF(MINUTE, @dt, starttime)between @basedTime and @earliestTime

我想要的是..我想一次又一次地进行查询,直到@earliestTime&gt; @latestTime

我知道我应该使用存储过程..但我不知道如何使用它..

1 个答案:

答案 0 :(得分:1)

试试这个

create table #temp TicketIssued numeric(9), Period datetime,
CalledTickets numeric(9), LessThanAcceptedWaitingTime numeric(9);

while(@earliestTime > @latestTime)
begin
set @earliestTime=@earliestTime+@AddTime;
insert into #temp
(SELECT 
count(DATEDIFF(MINUTE, @dt, starttime)) as 'Ticket Issued',
@earliestTime as 'Period',
count(DATEDIFF(MINUTE, @dt, nexttime)) as 'Called Tickets',
SUM(case when DATEDIFF(second, starttime, nexttime) <=900 then 1 else 0 end) as 'Less than Accepted Waiting Time'
from visit
where DATEDIFF(MINUTE, @dt, starttime)between @basedTime and @earliestTime)
end

select * from #temp

希望这会有所帮助