日期:2014-05-17  浏览次数:20684 次

sql如何按条件删除大量数据(面试题)
今天碰到一个面试题:

有一个Student表有ID,Class,Name,Sex四个字段,要求删除Class =‘0903’,Sex =‘M' 的所有记录(满足条件的记录超过3万)

听说应该用分段处理,但是多次尝试都没有成功,所以向大侠请教!

------解决方案--------------------
按id分段删除.

DECLARE @i INT
SET @i=5000
DELETE STUDENT WHERE ID<@i AND Class ='0903' AND Sex ='M' 
WHILE @@ROWCOUNT>0
BEGIN
BEGIN TRAN
SET @i=@i+5000
DELETE STUDENT WHERE ID<@i AND Class ='0903' AND Sex ='M'
COMMIT TRAN
END
------解决方案--------------------

SQL code
SET ROWCOUNT 100
WHILE 1=1
BEGIN
    DELETE FROM Student WHERE lass ='0903' AND Sex ='M'
    IF @@ROWCOUNT<100 BREAK
END

WHILE 1=1
BEGIN
    DELETE TOP (100) FROM Student WHERE lass ='0903' AND Sex ='M'
    IF @@ROWCOUNT<100 BREAK
END

------解决方案--------------------
SQL code
--2000 or 2005
set rowcount 5000
DELETE STUDENT WHERE Class ='0903' AND Sex ='M'
WHILE @@ROWCOUNT>0
BEGIN
    DELETE STUDENT WHERE Class ='0903' AND Sex ='M'
END
set rowcount 0