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) |