问题
Is it possible to set the result from a prepared statement into a variable? I am trying to create the following stored procedure but it is failing:
ERROR 1064 (42000) at line 31: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '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 ;
回答1:
It may seem strange, but you can assign the variable directly in the prepared statement string:
PREPARE stmt FROM 'SELECT @i := id FROM ...';
-- ...
EXECUTE stmt USING @m, @c, @a;
-- @i will hold the id returned from your query.
Test case:
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 ;
Result:
CALL myProc(400);
+---------+
| result |
+---------+
| 4 |
+---------+
1 row in set (0.00 sec)
回答2:
Use this code
PREPARE stmt FROM 'SELECT ''a'' into @i' ;
EXECUTE stmt;
if(@i='a') then
............
end if;
回答3:
not even sure why you're using dynamic sql in your example - this seems a lot simpler
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');
来源:https://stackoverflow.com/questions/3992454/how-to-get-scalar-result-from-prepared-statement