载入中
自定义HTML载入中... loading
mssql2000清空全部表数据的存储过程 [原创 2007-09-22 11:17:26]  删除... 
字体变小 字体变大

由于一些外键的约束关系,使全部表数据的删除变的很困难,通常需要执行多次的批量删除才可以完全清除.这里的存储过程考虑到了外键的约束关系,使表数据按照外键约束的先后顺序来删除表内容.一次执行即可删除全部数据

create proc sp_detall
as
begin tran
declare @id int
declare @sql varchar(200)
declare @num int,@numed int
declare @deted table(id int not null)
declare @notdeted table(id int not null)
insert into @notdeted select id from   sysobjects where xtype='u'

--这里可以加一些限制条件,保留一些表的数据,但要注意约束关系

insert into @deted
  select id from @notdeted where  id not in (select distinct rkeyid from sysforeignkeys)
declare mycursor cursor for select id from @deted
open mycursor
fetch next from mycursor into @id
while(@@fetch_status=0)
begin
 select @sql='delete from '+name from sysobjects where  id=@id
 exec(@sql)
 fetch next from mycursor into @id
end
close mycursor
deallocate mycursor

select @num=count(1) from  @notdeted
select @numed=count(1) from  @deted

while (@numed<@num)
begin
 delete from @notdeted where id in (select id from @deted)
 declare mycursor cursor for
  select id from @notdeted a where (select count(1) from sysforeignkeys where rkeyid=a.id and fkeyid  in (select id from @notdeted))=0
 open mycursor
 fetch next from mycursor into @id
 while(@@fetch_status=0)
 begin
  select @sql='delete from '+name from sysobjects where  id=@id
  exec(@sql)
  insert into @deted select @id
  fetch next from mycursor into @id
 end
 close mycursor
 deallocate mycursor
 select @numed=count(1) from  @deted
end

commit

票数:
什么是“我顶”?
点击数:    评论数:
本文章引用通告地址(TrackBack Ping URL)为:
本文章尚未被引用。
上一篇: 发烧了
发表评论
大 名:
(不填写则显示为匿名者)
网 址:
(您的网址,可以不填)
标 题:
内 容:
请根据下图中的字符输入验证码:
(您的评论将有可能审核后才能发表)
和讯个人门户 v1.0 | 和讯部落 | 客服中心