如何在同一例程中使用两个游标?如果我删除了第二个游标声明并获得了循环,一切都会正常工作。这个例程用于我webapp添加朋友。它使用当前用户ID以朋友的电子邮件为朋友,然后检查电子邮件是否有相应的用户ID,如果没有朋友,它会创造一个。除此之外,任何其他常规解决方案都很好。0 [5 h4 p8 ?$ x7 E7 ], P
DROP PROCEDURE IF EXISTS addNewFriend;DELIMITER //CREATE PROCEDURE addNewFriend(IN inUserId INT UNSIGNED,IN inFriendEmail VARCHAR(80))BEGIN DECLARE tempFriendId INT UNSIGNED DEFAULT 0; DECLARE tempId INT UNSIGNED DEFAULT 0; DECLARE done INT DEFAULT 0; DECLARE cur CURSOR FOR SELECT id FROM users WHERE email = inFriendEmail; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN cur; REPEAT FETCH cur INTO tempFriendId; UNTIL done = 1 END REPEAT; CLOSE cur; DECLARE cur CURSOR FOR SELECT user_id FROM users_friends WHERE user_id = tempFriendId OR friend_id = tempFriendId; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN cur; REPEAT FETCH cur INTO tempId; UNTIL done = 1 END REPEAT; CLOSE cur; IF tempFriendId != 0 AND tempId != 0 THEN INSERT INTO users_friends (user_id,friend_id) VALUES(inUserId,tempFriendId); END IF; SELECT tempFriendId as friendId;END //DELIMITER ; ; ; d$ D; _, Y: q7 ~+ i0 u/ D: ^' {解决方案: " N4 C6 I5 }9 B- |; Z
我终于写了一个执行相同功能的不同函数: 8 y8 q6 _4 [. uDROP PROCEDURE IF EXISTS addNewFriend;DELIMITER //CREATE PROCEDURE addNewFriend(IN inUserId INT UNSIGNED,IN inFriendEmail VARCHAR(80))BEGIN SET @tempFriendId = (SELECT id FROM users WHERE email = inFriendEmail); SET @tempUsersFriendsUserId = (SELECT user_id FROM users_friends WHERE user_id = inUserId AND friend_id = @tempFriendId); IF @tempFriendId IS NOT NULL AND @tempUsersFriendsUserId IS NULL THEN INSERT INTO users_friends (user_id,friend_id) VALUES(inUserId,@tempFriendId); END IF; SELECT @tempFriendId as friendId;END //DELIMITER ;我希望这是一个更好的解决方案,无论如何都能正常工作。谢谢你告诉我不要在不需要的时候使用游标。