使用while循环使用存储过程批量更新

时间:2014-03-12 09:09:35

标签: mysql sql stored-procedures mysql-workbench

我想用一些优化更新一个包含数百万条记录的表,但我无法创建一个程序。我的脚本是

DROP PROCEDURE IF EXISTS test_f;
Delimiter //
create procedure test_f()
begin
DECLARE i INT unsigned DEFAULT 1;
while i < 10 do
update top 2000 test t
set 
t.total = 123

where t.total=0;
set i = i+1;
end while;      


END //

我如何在我的程序中使用top或limit。

1 个答案:

答案 0 :(得分:0)

您可以将limitupdate声明一起使用。

DROP PROCEDURE IF EXISTS test_f;

Delimiter //

create procedure test_f()
begin
    DECLARE i INT unsigned DEFAULT 1;
    while i < 10 do
        update test t
        set t.total = 123
        where t.total=0
        limit 2000;

        set i = i+1;
    end while;      
end;
//

delimiter ;

以上程序仅导致更新首次发现的 2000记录 如果要更新2000和plus之间的记录,则需要在limit子句中指定,例如limit 2000, 2000,用于更新行号从2001到4000的记录。

相关问题