简体   繁体   中英

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:

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.

My 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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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