The following five problems were solved
1. Empty data
2. There is a foreign key can also, because it is reverse delete, from the last table deleted. And the delete is used because truncate cannot pair a table with a foreign key
3. Seed problem, if the table exists seed reset to 0, if not present do not operate
4. Added business, the middle of the error, there is regret opportunity
5. Truncate log function, because use Delete, the log file will increase after deletion, you can not use
[CPP] View Plain Copy if ( object_id (' pr_dataclear ') is not null ) drop procedure pr_DataClear go CREATE PROCEDURE PR _dataclear as begin transaction declare @ Ctblname varchar (128) declare cur_clear cursor for select rtrim (name) from sysobjects where type = ' U ' order by crdate desc open cur_Clear declare @cSQL varchar (255) fetch next from cur_clear into @cTblName while ( @ @fetch_status = 0 ) begin set @cSQL &Nbsp;= ' delete from ' + @cTblName print @cSQL exec ( @cSQL ) if ( ident_seed (@cTblName) is not null ) begin dbcc checkident ( @cTblName, reseed, 0 ) print ' Have seed and successfully reset to 1 ' end fetch next from cur_Clear into @cTblName end close cur_Clear deallocate cur_Clear commit go -- Clear all table data exec pr_dataclear -- truncate log backup log lz database with no_log dbcc Shrinkdatabase ( lz database ) dbcc updateusage ( lz database ) -- View tablespace (estimate) Select object_name (ID) as table name, (RTrim (8*reserved/1024) + ' MB ') as total, (RTrim (8*dpages/1024) + ' MB ') as used, (RTrim (8* (reserved-dpages)/1024) + ' MB ') as unused, (RTrim rows/1024*minlen/1024) + ' MB ' ) as void from sysindexes where indid=1 order by reserved desc
Original source: http://topic.csdn.net/u/20090816/17/EE0FA21E-8616-4236-A9CB-8C5A3D45C9D9.html 45 Floor
For tables with foreign KEY constraints, the online approach is generally:
EXEC sp_msforeachtable ' ALTER TABLE? NOCHECK CONSTRAINT All '--NOCHECK Const
EXEC sp_msforeachtable ' truncate TABLE? '
EXEC
sp_msforeachtable
'
ALTER TABLE? CHECK CONSTRAINT
All--
NOCHECK Constraints
is not feasible because
Trun
Cate cannot change to a table with a foreign key, delete from TableName is OK, but delete activates the trigger, which is also a problem.