MySQL stored procedure, handling multiple cursors and query results

前端 未结 5 1389

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 09:03

    Rather than using cursors to check for the existence of records, you can use the EXISTS clause in the WHERE clause:

    INSERT INTO users_friends 
      (user_id, friend_id) 
    VALUES
      (inUserId, tempFriendId)
    WHERE EXISTS(SELECT NULL 
                   FROM users 
                  WHERE email = inFriendEmail)
      AND NOT EXISTS(SELECT NULL 
                       FROM users_friends 
                      WHERE user_id = tempFriendId 
                        AND friend_id = tempFriendId);
    

    I made an alteration after reading Paul's comments about the second query, and reversed the logic so the insert won't add duplicates. Ideally this should be handled as a primary key being a compound key (including two or more columns), which would stop the need for checking in code.

提交回复
热议问题