在存储过程中循环执行语句

时间:2012-11-20 00:47:55

标签: mysql stored-procedures insert execute

我有以下方案:

CREATE DEFINER=`test`@`%` PROCEDURE `prTest`()
BEGIN
     SET @prepared_sql = 'select field1, field2 from table_data1');

     PREPARE stmt FROM @prepared_sql;
     EXECUTE stmt;
     DEALLOCATE PREPARE stmt;
END

我必须在循环中打开“stmt”。如何读取此循环和每一行,获取“field1”和“field2”的值并将值插入另一个表中?

1 个答案:

答案 0 :(得分:-1)

解决:

CREATE DEFINER=`test`@`%` PROCEDURE `prTest`()
BEGIN
     SET @prepared_sql = 'insert into table_data2
                          select field1, field2 from table_data1');

     PREPARE stmt FROM @prepared_sql;
     EXECUTE stmt;
     DEALLOCATE PREPARE stmt;
END