1、脚本说明
此脚本用于清空数据库数据,只删除相关表记录,保留表结构及存储过程触发器等主要架构。
设计思路:
1)根据表添加时间逆向获取所有用户表信息
2)使用游标循环删除每张表内数据
3)使用delete进行删除,即使有外键关系同样可以删除表记录
4)表存在自增主键则将其重置为0
5)截断日志,将数据库表空间及日志文件缩减到最小
2、使用说明
1)建立删除数据库存储过程SP_DaTaBaSeClear
以下是代码片段: If( object_id('SP_DaTaBaSeClear') is not null ) drop procedure SP_DaTaBaSeClear go SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROCEDURE SP_DaTaBaSeClearASBegin Transaction declare @BtableName varchar(200) declare curDel cursor for select rtrim(name) from sysobjects where type = 'U' order by crdate desc open curDel declare @delSQL varchar(500) fetch next from curDel into @BtableName while( @@fetch_status = 0) begin set @delSQL = 'delete from ' + @BtableName print @delSQL exec( @delSQL ) if( ident_seed(@BtableName) is not null ) begin dbcc checkident( @BtableName, reseed, 0 ) print '种子成功置为1' end fetch next from curDel into @BtableName end close curDel deallocate curDel Commit GO |
2)执行该存储过程,执行过程中查看执行信息,如有红色信息则先手动删除红色信息表记录
-- 执行存储过程删除表数据
EXEC SP_DaTaBaSeClear
3)如仍然报出红色信息则直接执行以下语句进行删除
以下是代码片段: declare @BtableName varchar(128) declare curDel cursor for select rtrim(name) from sysobjects where type = 'U' order by crdate desc open curDel declare @delSQL varchar(255) fetch next from curDel into @BtableName while( @@fetch_status = 0) begin set @delSQL = 'delete from ' + @BtableName print @delSQL exec( @delSQL ) if( ident_seed(@BtableName) is not null ) begin dbcc checkident( @BtableName, reseed, 0 ) print '种子成功置为1' end fetch next from curDel into @BtableName end close curDel deallocate curDel |
4)最后执行脚本重置数据库大小
以下是代码片段: backup log @DataBaseName with no_log dbccshrinkdatabase(@DataBaseName) dbccupdateusage(@DataBaseName) |