gpt4 book ai didi

mysql - MYSQL存储过程中循环select查询结果集

转载 作者:行者123 更新时间:2023-11-29 12:22:19 38 4
gpt4 key购买 nike

如何循环查询的结果集并在循环结果集中获取列值并在数据库上触发插入查询。

下面是我的 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;

然后如何循环stmt1以获取所有ID值以插入到另一个表中。

我的 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

但它给出错误子查询返回超过1行

最佳答案

最后我将存储过程编写为:

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

关于mysql - MYSQL存储过程中循环select查询结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28830527/

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