MySQL存储过程,处理多个游标和查询结果

编程入门 行业动态 更新时间:2024-10-21 11:53:55
本文介绍了MySQL存储过程,处理多个游标和查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在同一例程中使用两个游标?如果我删除了第二个游标声明并获取了循环,一切都将正常工作.该例程用于在我的webapp中添加朋友.它使用当前用户的ID和我们要添加的朋友的电子邮件作为朋友,然后检查电子邮件是否具有相应的用户ID,如果不存在朋友关系,它将创建一个.除此以外的任何其他常规解决方案也都很好.

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 webapp. It takes the id of the current user and the email of the friend we want to add as a friend, then it checks if the email has a corresponding user id and if no friend relation exists it will create one. Any other routine solution than this one would be great as well.

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 ;

推荐答案

我终于编写了一个执行相同功能的不同函数:

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.

更多推荐

MySQL存储过程,处理多个游标和查询结果

本文发布于:2023-10-13 10:15:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1487670.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   游标   查询结果   存储过程   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!