开发者

delete large amount of data

i have to delete a large amount of data. truncate is not possible because of relations. And I don't wanna drop the table because of views. I am using 开发者_C百科code below but is there better idea?

delete from table
WHILE 1=1
BEGIN
BEGIN TRAN
DELETE  top (1000000) from table
IF @@rowcount < 1000000 BREAK
WAITFOR DELAY '00:00:00:010'
COMMIT
end  
DELETE  from table


Truncate table would be the best by far.

If you're worried about relationships because of the referencial integrity, than I suggest you update separately those tables that reference it by foreign key (e.g. if foreign keys have ON DELETE SET NULL then UPDATE RefTbl SET Key = NULL WHERE Key IS NOT NULL, similarly, delete if cascade etc...).

Alternatively, if you don't want that, you can alter your query to be a bit quicker by using ROWCOUNT:

--other code for loop
SET ROWCOUNT 1000000 --this limits the number of rows that will be processed
DELETE FROM Table1

Also, I'm not sure why are you doing this inside a transaction? It would create a huge transaction log and impact your performance severely... When you're performing stuff like dumping table content usually transactions are not relevant (it could be relevant in your case, but I'm just saying it's rarely the case). If you do need transaction, than at least move your delay out of it...


You could do it a bit simpler:

delete table where id in (select top 1000000 id from table)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜