简体   繁体   English

在MYSQL存储过程中循环选择查询结果集

[英]Loop the select query result set in MYSQL Stored Procedure

How to loop the resultset of query and in loop the resultset get the column value and fire insert query on database. 如何循环查询结果集和循环结果集以获取列值并在数据库上执行插入查询。

Below is My SP: 以下是我的SP:

Input parameter listvalues and value is 1,2,3,4,5

SET @t1 = CONCAT("SELECT ID FROM interest WHERE ID IN(",listvalues,")");
PREPARE stmt1 FROM @t1;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

Then how to loop the stmt1 to get all ID values to insert in another table. 然后如何循环stmt1以获得所有ID值以插入到另一个表中。

My SP: 我的SP:

BEGIN 
INSERT INTO `registration`(`FirstName`,`LastName`,`EMail`,`PhoneNumber`,`Gender`,`State`,`City`,`ImagePath`,`IsDeleted`,`CreatedDate`,`ModifiedDate`)
VALUES(FirstName,LastName,EMail,PhoneNumber,Gender,State,City,ImagePath,0,NOW(),NOW());

SET @RegID = LAST_INSERT_ID();

SET @t1 = CONCAT("INSERT INTO `userinterest` (`InterestId` , `UserId`) VALUES((SELECT ID FROM interest WHERE ID IN(",InterestList,")),",@RegID,")");
PREPARE stmt3 FROM @t1;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;

END

But it give error Subquery returns more than 1 row 但是它给错误子查询返回超过1行

Finally I've write stored procedure as: 最后,我将存储过程编写为:

BEGIN 
INSERT INTO `registration`(`FirstName`,`LastName`,`EMail`,`PhoneNumber`,`Gender`,`State`,`City`,`ImagePath`,`IsDeleted`,`CreatedDate`,`ModifiedDate`)
VALUES(FirstName,LastName,EMail,PhoneNumber,Gender,State,City,ImagePath,0,NOW(),NOW());

SET @RegID = LAST_INSERT_ID();

SET @t1 = CONCAT("INSERT INTO `userinterest` (`InterestId` , `UserId`) SELECT ID AS InterestId, ",@RegID," AS UserId FROM interest WHERE ID IN(",InterestList,")");
PREPARE stmt3 FROM @t1;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;

END

Do the INSERT in the query: 在查询中执行INSERT

SET @t1 = CONCAT("INSERT INTO otherTable (interest_id)
                  SELECT ID FROM interest WHERE ID IN(",listvalues,")");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM