是否可以将预准备语句的结果设置为变量?我正在尝试创建以下存储过程,但它失败了:
第31行的错误1064(42000):您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在'stmt USING @m,@ c,@ a;
附近使用正确的语法
DROP PROCEDURE IF EXISTS deleteAction;
DELIMITER $$
CREATE PROCEDURE deleteAction(
IN modul CHAR(64),
IN controller CHAR(64),
IN actn CHAR(64))
MODIFIES SQL DATA
BEGIN
PREPARE stmt FROM 'SELECT id
FROM actions
WHERE `module` = ?
AND `controller` = ?
AND `action` = ?';
SET @m = modul;
SET @c = controller;
SET @a = actn;
SET @i = EXECUTE stmt USING @m, @c, @a;
DEALLOCATE PREPARE stmt;
DELETE FROM acl WHERE action_id = @i;
DELETE FROM actions WHERE id = @i;
END
$$
DELIMITER ;
答案 0 :(得分:6)
看起来很奇怪,但您可以直接在预准备语句字符串中分配变量:
PREPARE stmt FROM 'SELECT @i := id FROM ...';
-- ...
EXECUTE stmt USING @m, @c, @a;
-- @i will hold the id returned from your query.
测试用例:
CREATE TABLE actions (id int, a int);
INSERT INTO actions VALUES (1, 100);
INSERT INTO actions VALUES (2, 200);
INSERT INTO actions VALUES (3, 300);
INSERT INTO actions VALUES (4, 400);
INSERT INTO actions VALUES (5, 500);
DELIMITER $$
CREATE PROCEDURE myProc(
IN p int
)
MODIFIES SQL DATA
BEGIN
PREPARE stmt FROM 'SELECT @i := id FROM actions WHERE `a` = ?';
SET @a = p;
EXECUTE stmt USING @a;
SELECT @i AS result;
DEALLOCATE PREPARE stmt;
END
$$
DELIMITER ;
结果:
CALL myProc(400);
+---------+
| result |
+---------+
| 4 |
+---------+
1 row in set (0.00 sec)
答案 1 :(得分:2)
使用此代码
PREPARE stmt FROM 'SELECT ''a'' into @i' ;
EXECUTE stmt;
if(@i='a') then
............
end if;
答案 2 :(得分:1)
甚至不确定为什么你在你的例子中使用动态sql - 这似乎更简单
drop procedure if exists deleteAction;
delimiter #
create procedure deleteAction
(
in p_modul char(64),
in p_controller char(64),
in p_actn char(64)
)
begin
declare v_id int unsigned default 0;
select id into v_id from actions where
module = p_modul and controller = p_controller and action = p_actn;
delete from acl where action_id = v_id;
delete from actions where id = v_id;
select v_id as result;
end #
delimiter ;
call deleteAction('mod','ctrl','actn');