在存储过程方面,我不是最有知识的人,这个问题让我大吃一惊!
基本上我只是想运行一个简单的更新语句,但是当我在过程中运行它时,我选择更新行的用户 ID 不正确,但如果我在过程外运行相同的选择语句,它返回预期结果。
DELIMITER $$
CREATE PROCEDURE catchUpBbs_Users()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE deleteUser, keepUser VARCHAR(255);
DECLARE id INT;
DECLARE cur1 CURSOR FOR SELECT u.username, b.username, b.id from users u RIGHT JOIN bbs_users b ON u.username = b.username WHERE u.username IS NULL;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
allusers: LOOP
FETCH cur1 INTO keepUser, deleteUser, id;
IF done THEN
LEAVE allusers;
END IF;
IF deleteUser != 'anonymous' THEN
-- This is where the problems start
-- Just for test purposes, returns correct id and username
SELECT id, username FROM bbs_users WHERE username = deleteUser;
-- Just for test purposes, return INCORRECT id, but the CORRECT username
SELECT id, username FROM bbs_users WHERE username = 'anonymous';
-- The update statement that does not work as I want it to, sets the user_id to be what it already it, so no updates occur
UPDATE bbs_posts SET user_id = (SELECT id FROM bbs_users WHERE username = 'anonymous') WHERE user_id = (SELECT id FROM bbs_users WHERE username = deleteUser);
-- delete the user from the bbs_users table
DELETE FROM bbs_users WHERE username = deleteUser;
END IF;
END LOOP allusers;
CLOSE cur1;
END;
$$
DELIMITER ;
当我调用过程时,两个测试选择语句返回:
1) 这些结果都是正确的
SELECT id, username FROM bbs_users WHERE username = deleteUser;
+------+----------+
| id | username |
+------+----------+
| 13 | deleteme |
+------+----------+
2)ID不对,但是用户名不对,ID应该是1
SELECT id, username FROM bbs_users WHERE username = 'anonymous';
+------+-----------+
| id | username |
+------+-----------+
| 13 | anonymous |
+------+-----------+
当我运行相同的,减去变量,过程外的选择语句都返回正确的结果
1) 这些结果都是正确的
SELECT id, username FROM bbs_users WHERE username = 'deleteme';
+----+----------+
| id | username |
+----+----------+
| 13 | deleteme |
+----+----------+
2) 这些结果都是正确的
SELECT id, username FROM bbs_users WHERE username = 'anonymous';
+----+-----------+
| id | username |
+----+-----------+
| 1 | anonymous |
+----+-----------+
我做错了什么?在使用存储过程时涉及选择和变量时,我是否遗漏了什么?
任何帮助或建议将不胜感激
最佳答案
问题是您在游标中定义了一个名为 id
的标量变量,并且您正在选择它,因此游标内的两个选择语句都使用该存储的标量值对 id
的引用。
为了获得“正确”的值,您需要消除所有歧义:
-- Just for test purposes, returns correct id and username
SELECT b.id, b.username FROM bbs_users b WHERE b.username = deleteUser;
-- Just for test purposes, return INCORRECT id, but the CORRECT username
SELECT b.id, b.username FROM bbs_users b WHERE b.username = 'anonymous';
关于MYSQL存储过程select语句select不正确的ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9367342/