admin管理员组文章数量:1125023
Problem: The loop is not executed after the first loop.
CREATE PROCEDURE IF NOT EXISTS chunk_delete(IN table_name varchar(255), IN loop_count int, IN batch_size int)
BEGIN
DECLARE counter INT DEFAULT 0;
DECLARE rows_affected INT DEFAULT 1;
DECLARE delete_query TEXT;
WHILE counter <= loop_count AND rows_affected > 0 DO
SET delete_query = CONCAT('DELETE FROM ', table_name, ' LIMIT ', batch_size);
SELECT delete_query;
SET @sql_query = delete_query;
PREPARE stmt FROM @sql_query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET rows_affected = ROW_COUNT();
SET counter = counter + 1;
END WHILE;
END
Expected Result: If the loop_count is 4 and batch_size is 10, the result is deletion of 40 rows after 4 loops. However, the loop is not implemented after deletion of first batch size of 10 rows.
Problem: The loop is not executed after the first loop.
CREATE PROCEDURE IF NOT EXISTS chunk_delete(IN table_name varchar(255), IN loop_count int, IN batch_size int)
BEGIN
DECLARE counter INT DEFAULT 0;
DECLARE rows_affected INT DEFAULT 1;
DECLARE delete_query TEXT;
WHILE counter <= loop_count AND rows_affected > 0 DO
SET delete_query = CONCAT('DELETE FROM ', table_name, ' LIMIT ', batch_size);
SELECT delete_query;
SET @sql_query = delete_query;
PREPARE stmt FROM @sql_query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET rows_affected = ROW_COUNT();
SET counter = counter + 1;
END WHILE;
END
Expected Result: If the loop_count is 4 and batch_size is 10, the result is deletion of 40 rows after 4 loops. However, the loop is not implemented after deletion of first batch size of 10 rows.
Share Improve this question asked 2 days ago yoooooyooooo 32 bronze badges New contributor yooooo is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 1- What is the value of rows_affected first time through? – P.Salmon Commented 2 days ago
1 Answer
Reset to default 0ROW_COUNT() is called after DEALLOCATE PREPARE
statement. So it returns 0. And WHILE cycle breaks.
Even if you get the value immediately after EXECUTE, the function will still return 0. Because DELETE statement and EXECUTE statement which executes DELETE is not the same.
If you want to know how many rows were deleted with EXECUTE then you'd count the amount of rows in the table before and after the prepared statement execution. Also you'd block the concurrent processes changes.
And you do not need to prepare and deallocate each loop - prepare before and drop after.
本文标签: mysqlStored Procedure for Deleting in ChunksLOOP not executingStack Overflow
版权声明:本文标题:mysql - Stored Procedure for Deleting in Chunks - LOOP not executing - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736651063a1946141.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论