MySQL stored procedure, handling multiple cursors and query results

前端 未结 5 1370

How can I use two cursors in the same routine? If I remove the second cursor declaration and fetch loop everthing works fine. The routine is used for adding a friend in my webap

5条回答
  •  庸人自扰
    2021-02-14 08:59

    I have finally written a different function that does the same thing:

    DROP 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 ;
    

    I hope this is a better solution, it works fine anyway. Thanks for telling me not to use cursors when not necessary.

提交回复
热议问题