declare @app as varchar(10),@prevapp as varchar(10),@ts as datetime
declare @event_type as int,@concurrent as int ,@mx as int
declare @result table(app varchar(10),mx int)
declare c cursor fast_forward for
select app,starttime as ts, 1 as event_type  from dbo.sessions
union all
select app,endtime,-1 from dbo.sessions order by app,event_type;
open c
fetch next from c into @app,@ts,@event_type;
select @prevapp=@app,@concurrent=0,@mx=0; /*这里把@prevapp的值赋值给@app了,两个变量的值是一样了*/
while @@fetch_status=0                               
begin
if @app<>@prevapp    --这里要两个变量不一样才能执行语句阿。可是上面是一样的为啥也执行了。
begin
insert into @result values(@prevapp,@mx);
select @prevapp=@app,@concurrent=0,@mx=0
end
set @concurrent=@concurrent+@event_type;
if @concurrent>@mx set @mx=@concurrent;
fetch next from c into @app,@ts,@event_type
end
if @prevapp is not null
insert into @result values(@prevapp,@mx);
close c 
deallocate c
select * from @result;

解决方案 »

  1.   


    @app 之前是没赋值的。肯定是NULL
    但后面用select赋值了。就不是NULL ,而是和@prevapp一样了。
      

  2.   

    select app,starttime as ts, 1 as event_type  from dbo.sessions
    union all
    select app,endtime,-1 from dbo.sessions order by app,event_type;这里边app是否有NULL。当然,楼主也可以做个测试,将app starttime  endtime event_type 等字段用一个具体值表示,看看执行出得到什么,一步步分析下。
      

  3.   


    这个可以肯定的告诉你,游标集里面根本就没有NULL存在。
    全是具体的数据。
      

  4.   

    app        ts                      event_type
    ---------- ----------------------- -----------
    app1       2006-02-12 08:45:00.000 -1
    app1       2006-02-12 10:30:00.000 -1
    app1       2006-02-12 09:30:00.000 -1
    app1       2006-02-12 09:30:00.000 -1
    app1       2006-02-12 10:30:00.000 -1
    app1       2006-02-12 14:30:00.000 -1
    app1       2006-02-12 11:30:00.000 -1
    app1       2006-02-12 12:30:00.000 -1
    app1       2006-02-12 08:30:00.000 1
    app1       2006-02-12 08:30:00.000 1
    app1       2006-02-12 09:00:00.000 1
    app1       2006-02-12 09:15:00.000 1
    app1       2006-02-12 09:15:00.000 1
    app1       2006-02-12 10:30:00.000 1
    app1       2006-02-12 10:45:00.000 1
    app1       2006-02-12 11:00:00.000 1
    app2       2006-02-12 08:45:00.000 -1
    app2       2006-02-12 09:30:00.000 -1
    app2       2006-02-12 12:00:00.000 -1
    app2       2006-02-12 14:00:00.000 -1
    app2       2006-02-12 13:30:00.000 -1
    app2       2006-02-12 14:00:00.000 -1
    app2       2006-02-12 16:30:00.000 -1
    app2       2006-02-12 17:00:00.000 -1
    app2       2006-02-12 08:30:00.000 1
    app2       2006-02-12 09:00:00.000 1
    app2       2006-02-12 11:45:00.000 1
    app2       2006-02-12 12:30:00.000 1
    app2       2006-02-12 12:45:00.000 1
    app2       2006-02-12 13:00:00.000 1
    app2       2006-02-12 14:00:00.000 1
    app2       2006-02-12 15:30:00.000 1(32 行受影响)
      

  5.   

    擦,不是子查询或者递归的问题。我想知道它是怎么执行的。TRVY,给个答案呗。