Bulk delete (truncate vs delete)

蹲街弑〆低调 提交于 2019-11-30 18:55:43

truncate is what you're looking for. If you need to slim down the db afterwards, run a shrink.

This MSDN refernce (if you're talking T-SQL) compares the behind the scenes of deleting rows versus truncating.

"Delete all rows"... wouldn't DROP TABLE (and re-recreate an empty one with same schema / indices) be preferable ? (I personally like "fresh starts" ;-) )

This said TRUNCATE TABLE is quite OK too, and yes, DBCC SHRINKFILE may be required afterwards if you wish to recover the space.

Depending on the size of the full database, the shrink may take a while; I've found it to go faster if it is shrunk in smaller chunks, rather than trying to get it back all at once.

One thing to remember with Truncate Table (as well as drop table) is going forward this will not work if you ever have foreign keys referencing the table.

As pointed out, if you can't use truncate or drop

SELECT 1
WHILE @@ROWCOUNT <> 0
    DELETE TOP (100000) MyTable
Chad

You have a normal solution (truncate + shrink db) to remove all the records from a table.

As Irwin pointed out. The TRUNCATE command won't work while being referenced by a Foreign key constraint. So first drop the constraints, truncate the table and recreate the constraints.

If your concerned about performance and this is a regular routine for your system. You might want to look into moving this table to it's own data file, then run shrink only against the target datafile!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!