【发布时间】:2012-03-11 03:50:52
【问题描述】:
在存储过程方面,我不是知识最渊博的人,这个问题让我大吃一惊!
基本上我只是想运行一个简单的更新语句,但是当我在过程中运行它时,我选择更新行的用户 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 |
+------+-----------+
当我运行相同的程序时,减去变量,过程外的 select 语句都返回正确的结果
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 |
+----+-----------+
我做错了什么?在使用存储过程时,在选择和变量方面有什么我错过的吗?
任何帮助或建议将不胜感激
【问题讨论】:
标签: mysql database stored-procedures select