保存数据库中其他对象不变,删除数据库中所有数据的实现方法

类别:数据库 点击:0 评论:0 推荐:

原帖内容:
怎样把数据库中所有数据删除,然后把所有的自动增量复位?
表太多,无法手工完成。
http://community.csdn.net/Expert/topic/3094/3094555.xml?temp=.2920954

/*
--原本打算这样
--先禁用所有外键约束
exec sp_msforeachtable "alter table ? nocheck CONSTRAINT all"
--然后删除数据
exec sp_msforeachtable "truncate table ?"
--再启用所有外键约束
exec sp_msforeachtable "alter table ? check constraint all"
--但是禁用了以后,truncate table 不行,会提示冲突
*/

--现在我的想法是(语句待优化):

--第一部分,生成建立外键的语句保存到#tmp
declare @name varchar(200),@tmp1 varchar(500),@tmp2 varchar(500)

create table #tmp
(
string varchar(8000)
)

SELECT  表名称=object_name(b.fkeyid)
 ,外键名称=a.name
 ,引用的列名=(SELECT name FROM syscolumns WHERE colid=b.fkey AND id=b.fkeyid)
 ,引用的表名=object_name(b.rkeyid)
 ,已引用的列名=(SELECT name FROM syscolumns WHERE colid=b.rkey AND id=b.rkeyid)
into #t FROM sysobjects a
 join sysforeignkeys b on a.id=b.constid
 join sysobjects c on a.parent_obj=c.id
where a.xtype='f' AND c.xtype='U'

declare cur_test cursor for
 select a.name from sysobjects a join sysobjects c on a.parent_obj=c.id where a.xtype='f' and c.xtype='U'
open cur_test
FETCH NEXT FROM cur_test INTO @name
WHILE (@@fetch_status <> -1)
BEGIN
 IF (@@fetch_status <> -2)
 BEGIN
  select @tmp1='',@tmp2=''
  select @tmp1=@tmp1+'['+引用的列名+'],',@tmp2=@tmp2+'['+已引用的列名+'],' from #t where 外键名称=@name
  insert into #tmp select top 1 'ALTER TABLE [DBO].['+表名称+'] ADD CONSTRAINT ['+@name+'] FOREIGN KEY ( '+left(@tmp1,len(@tmp1)-1)+' ) REFERENCES ['+引用的表名+'] ( '+left(@tmp2,len(@tmp2)-1)+' )' from #t where 外键名称=@name
 END
 FETCH NEXT FROM cur_test INTO @name
END

CLOSE cur_test
DEALLOCATE cur_test
drop table #t

--第二部分,删除所有外键
DECLARE @STRING VARCHAR(8000)
WHILE EXISTS(SELECT NAME FROM SYSOBJECTS WHERE TYPE='F')
BEGIN
 SELECT @STRING='ALTER TABLE '+B.NAME+' DROP CONSTRAINT '+A.NAME+CHAR(13)
  FROM (SELECT PARENT_OBJ,NAME FROM SYSOBJECTS WHERE TYPE='F') A,
        (SELECT ID,NAME FROM SYSOBJECTS WHERE OBJECTPROPERTY(ID, N'ISUSERTABLE') = 1) B
    WHERE A.PARENT_OBJ=B.ID
 EXEC(@STRING)
END

--第三部分,删除所有表的记录,并且把identity复位
exec sp_msforeachtable "truncate table ?"

--第4部分,执行#tmp里面的建立外键的语句,恢复外键
declare cur_test2 cursor for select string from #tmp

open cur_test2
FETCH NEXT FROM cur_test2 INTO @string
WHILE (@@fetch_status <> -1)
BEGIN
 IF (@@fetch_status <> -2)
 BEGIN
  exec(@string)
  PRINT @STRING
 END
 FETCH NEXT FROM cur_test2 INTO @string
END

CLOSE cur_test2
DEALLOCATE cur_test2

drop table #tmp

本文地址:http://com.8s8s.com/it/it20753.htm