现在数据库中有好几个月的历史数据需要清理,可是生产仍要继续,寻求一个方法来解决删除大量历史数据的同时,不影响生产的运转。如果简单的使用delete语句会严重影响生产,老大让我用游标来处理,写了一个游标,可是还没放在实时库上运行,麻烦高人帮忙看看,给点建议,谢谢!declare @id nvarchar(200),@sn nvarchar(50),@dtime datetime;
declare @cp table(id nvarchar(200),sn nvarchar(50),dtime datetime);declare test cursor fast_forward for 
select ID,SN,DTime from rt_Trace
where DTime<'2007-10-1 00:00'
and PackID is not nullopen test;
fetch next from test into @id,@sn,@dtime
insert into @cp values(@id,@sn,@dtime)
while @@fetch_status=0
begin 
fetch next from test into @id,@sn,@dtime
insert into @cp values(@id,@sn,@dtime)
endclose testdeallocate testselect * from @cpdelete rt_PackingDetail where id in (select id from @cp)
这样来删除数据库中大量历史数据会影响性能吗?
还有就是我游标中取出的记录中最后一条为什么是重复的啊?

解决方案 »

  1.   

    while @@fetch_status=0 
    begin 
    insert into @cp values(@id,@sn,@dtime) 
    fetch next from test into @id,@sn,@dtime 

    end游标本来就很慢,读取下条应该放在后面 的
      

  2.   

    这样不还好。declare @BKDateTime datetime
    set @BKDateTime=getdate()---或者你要的时间
    Declare @i int
    Declare @DelQty int
    set @i=0
    SET @DelQty =1000
    WHILE EXISTS(Select top 1 0 from rt_Trace where DTime<@BKDateTime)
    begin    
        delete top(@DelQty) FROM rt_Trace where DTime<@BKDateTime --不需要备份数据的话
        set @i=@i+1
    end  
      

  3.   


    现在效率低不低倒是无所谓,就是在操作删除数据时候不能出现阻塞,影响生产的运转,这是关键。你的这个code不是和用delete语句直接删除差不多吗?