MySQL 将 EXECUTE 的结果保存在变量中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2608668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL save results of EXECUTE in a variable?
提问by Egor Pavlikhin
How do I save the results of EXECUTE statement to a variable? Something like
如何将 EXECUTE 语句的结果保存到变量中?就像是
SET a = (EXECUTE stmtl);
回答by Ike Walker
If you want to do this with a prepared statement, then you need to include the variable assignment in the original statement declaration.
如果要使用准备好的语句执行此操作,则需要在原始语句声明中包含变量赋值。
If you want to use a stored routine it's easier. You can assign the return value of a stored function directly to a variable, and stored procedures support out parameters.
如果您想使用存储的例程,那就更容易了。您可以将存储函数的返回值直接分配给变量,并且存储过程支持输出参数。
Examples:
例子:
Prepared Statement:
准备好的声明:
PREPARE square_stmt from 'select pow(?,2) into @outvar';
set @invar = 1;
execute square_stmt using @invar;
select @outvar;
+---------+
| @outvar |
+---------+
| 1 |
+---------+
DEALLOCATE PREPARE square_stmt;
Stored Function:
存储功能:
delimiter $$
create function square_func(p_input int) returns int
begin
return pow(p_input,2);
end $$
delimiter ;
set @outvar = square_func(2);
select @outvar;
+---------+
| @outvar |
+---------+
| 4 |
+---------+
Stored Procedure:
存储过程:
delimiter $$
create procedure square_proc(p_input int, p_output int)
begin
set p_output = pow(p_input,2);
end $$
delimiter ;
set @outvar = square_func(3);
call square_proc(2,@outvar);
select @outvar;
+---------+
| @outvar |
+---------+
| 9 |
+---------+