SqlServer清空数据库中表数据让自增列从1开始(转)

--第一部分,生成建立外键的语句保存到#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

转载于:https://www.cnblogs.com/niaofei/archive/2009/08/18/1548649.html

你可能感兴趣的:(SqlServer清空数据库中表数据让自增列从1开始(转))