Bulk delete (truncate vs delete)

我的梦境 提交于 2019-11-30 03:11:10

问题


We have a table with a 150+ million records. We need to clear/delete all rows. Delete operation would take forever due to it writing to the t-logs and we cannot change our recovery model for the whole DB. We have tested the truncate table option.

What we realized that truncate deallocates pages from the table, and if I am not wrong makes them available for reuse but doesn't shrink the db automatically. So, if we want to reduce the DB size, we really would need to do run the shrink db command after truncating the table.

Is this normal procedure? Anything we need to be careful or aware about, or are there any better alternatives?


回答1:


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.




回答2:


"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.




回答3:


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.




回答4:


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.




回答5:


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

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



回答6:


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!



来源:https://stackoverflow.com/questions/1772984/bulk-delete-truncate-vs-delete

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