有人这样实现过。
--建立測試環境
create table A(id int,[time] datetime, log_id int, banch_id int)
insert into A select 1 ,'2008-8-20 14:30:00' ,1,1
insert into A select 1 ,'2008-8-20 14:30:00' ,1,1
insert into A select 1 ,'2008-8-20 14:30:00' ,1,1
insert into A select 2 ,'2008-8-20 15:30:00' ,1,1
insert into A select 3 ,'2008-8-20 16:30:00' ,1,1
insert into A select 3 ,'2008-8-20 17:30:00' ,1,1
GO
Create table B(id int, time1 varchar(10), time2 varchar(08), log_id int, banch_id int, num_id int)GO
--建立存儲過程
Create proc usp_test
AS
select tmp=identity(int,1,1) ,* into #t from Ainsert into B(num_id, id, time1,time2,log_id,banch_id)
select num_id=(select count(*) from #t  where  id=t1.id and [time]=t1.[time] and log_id=t1.log_id and banch_id=t1.banch_id and tmp<=t1.tmp)
          , id, convert(char(10),[time],120) as time1, convert(char(08),[time] ,108) as time2, log_id,banch_id
from #t  t1GO
--執行
exec usp_test
--查看結果
select * from B
/*
id          time1      time2    log_id      banch_id    num_id      
----------- ---------- -------- ----------- ----------- ----------- 
1           2008-08-20 14:30:00 1           1           1
1           2008-08-20 14:30:00 1           1           2
1           2008-08-20 14:30:00 1           1           3
2           2008-08-20 15:30:00 1           1           1
3           2008-08-20 16:30:00 1           1           1
3           2008-08-20 17:30:00 1           1           1
*/GO
drop proc usp_test
drop table A,B
现在需要通过游标的存储过程怎么实现?

解决方案 »

  1.   

    试试下面的代码select id,
    time,
    log_id,
    banch_id
    num_id = identity(int,1,1)
    into #t
    from table_A
    order by id,time,log_id,banch_id
    goselect id,
    time,
    log_id,
    banch_id,
    min(num_id) num_id
    into #t1
    from #t
    group by id,
    time,
    log_id,
    banch_id
    goupdate #t
    set num_id = a.num_id - b.num_id+1
    from #t a,#t1 b
    where a.id = b.id
    and a.time = b.time
    and a.log_id   = b.log_id     
    and     a.banch_id = b.banch_id
    goselect  id,                                       
             convert(char(10),time,120) as time1,    
             convert(char(8) ,time,108) as time2,                                        
             log_id,                                   
             banch_id,
             num_id 
    into table_B   
    from #t
    go
                                            
      

  2.   

    insert into B(num_id, id, time1,time2,log_id,banch_id) 
    select id,convert(varchar(10),[time],112),convert(varchar(10),[time],108)
    ,log_id,count(aa.num_id) from a,aa
    where aa.num_id=a.num_id
      

  3.   

      Tigersong :
        你的临时表用的太多了吧,如果数据量大的话,太占空间了。
       有没有人想过用游标实现呢?
      

  4.   

    我只是提供一个方案 FYI, 而且很明显你可以在第一步就拆分而省去一个临时表#t,后面的逻辑自己改一下即可
    如果这样的方案不可以的话, 以我的经验 用游标效率更差,IO和time都是需要考虑的问题