如何循环查询的结果集,并在循环中结果集获取数据库中的列值和触发插入查询。
以下是我的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行
答案 0 :(得分: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
答案 1 :(得分:0)
在查询中执行INSERT
:
SET @t1 = CONCAT("INSERT INTO otherTable (interest_id)
SELECT ID FROM interest WHERE ID IN(",listvalues,")");