gpt4 book ai didi

MySQL - 使用 WHILE DO 批量更新

转载 作者:行者123 更新时间:2023-11-29 17:25:55 25 4
gpt4 key购买 nike

有人可以告诉我我在这里做错了什么吗?

我不断收到您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在附近使用的正确语法...

我正在尝试小批量运行 UPDATE 命令,以防止表被阻塞(在运行 1000 万条记录时)。

DELIMITER //

CREATE FUNCTION batch_update()
BEGIN
SET processed = 0;
SET eachbatch = 1000;

WHILE processed < 1000000 DO
UPDATE `users` SET `active` = 1 WHERE `active` = 0 LIMIT eachbatch;

-- Finish when no rows remaining
IF ROW_COUNT() = 0 THEN LEAVE;
END IF;

-- No infinite loop, thanks
SET processed = processed + eachbatch;
END WHILE;
END //

DELIMITER ;

CALL batch_update();

编辑:对于任何需要指针的人,我的工作方式如下:

DROP FUNCTION IF EXISTS process_batch_rows;   

DELIMITER //
CREATE FUNCTION process_batch_rows() RETURNS VARCHAR(10) DETERMINISTIC
BEGIN
DECLARE processed INT DEFAULT 0;
DECLARE eachbatch INT DEFAULT 1000;

my_loop: WHILE processed < 1000000
DO
UPDATE `users` SET `active` = 1 WHERE `active` = 0 LIMIT eachbatch;

IF ROW_COUNT() < 1 THEN
LEAVE my_loop;
END IF;

SET processed = processed + eachbatch;
END WHILE my_loop;

RETURN "Done";
END //
DELIMITER ;

SELECT process_batch_rows();

最佳答案

试试这个,我在需要的地方添加了评论 =>

DELIMITER //

-- You must specify return type

CREATE FUNCTION batch_update() RETURNS VARCHAR(10) DETERMINISTIC

BEGIN

-- you must declare variables

DECLARE processed int(10);

DECLARE eachbatch int(10);

SET processed = 0;

SET eachbatch = 1000;

-- needed my loop here so it can be used in leave

myloop: WHILE processed < 1000000 DO

UPDATE `users` SET `active` = 1 WHERE `active` = 0 LIMIT eachbatch;

-- Finish when no rows remaining

IF ROW_COUNT() = 0

THEN

LEAVE myloop;

END IF;

-- No infinite loop, thanks

SET processed = processed + eachbatch;

END WHILE;

return 'Done';

END //

DELIMITER ;

关于MySQL - 使用 WHILE DO 批量更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50971039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com