mysql 存储过程

创建存储过程:

BEGIN和END之间的是核心,其他的是辅助语句。只关注这一部分即可,其他的都可以由工具生成后修改。
USE `test_csv`;  --test_csv is the table name
DROP procedure IF EXISTS `new_procedure`;
DELIMITER $$  --change delimiter
USE `test_csv`$$
CREATE DEFINER=`test_code`@`%` PROCEDURE `new_procedure`(OUT count INT)
BEGIN
select count(*) into count from minutes_data;
END$$
DELIMITER ;  --change back delimiter

调用存储过程:

传参数说明:

如果想获得存储过程中OUT或者INOUT参数的值,在调用的时候需要传入用户变量,然后在存储过程执行之后检查变量的值。

call new_procedure(@count);  --此处传变量count,获取存储过程的输出值

select @count;  -- get the value of the count, where count is the result of the procedure. 

存储过程调用时,存储过程中的IN参数可以直接传值,INOUT可以通过变量赋值传入,如果需要获取INOUT或者OUT的值,需要传变量,使用@variable_name的方式传变量。

INOUT使用示例:

USE `test_csv`;
DROP procedure IF EXISTS `new_procedure`;
DELIMITER $$
USE `test_csv`$$
CREATE DEFINER=`test_code`@`%` PROCEDURE `new_procedure`(INOUT count INT)
BEGIN
select count(*) into count from minutes_data;
END$$
DELIMITER ;

调用:

call new_procedure(@count);  --此处传变量count,获取存储过程的输出值 

select @count;  -- get the value of the count, where count is the result of the procedure. 

or:

set @count=1; --设置inout参数初始值 

call new_procedure(@count);  --获取存储过程改变后的inout参数的输出值

select @count;  -- get the value of the count, where count is the result of the procedure. 

IN和OUT配合使用:

USE `test_csv`;
DROP procedure IF EXISTS `new_procedure`;
DELIMITER $$
USE `test_csv`$$
CREATE DEFINER=`test_code`@`%` PROCEDURE `new_procedure`(IN limit_low int, OUT count INT)
BEGIN
SELECT count(*) INTO count FROM minutes_data WHERE ua > limit_low;
END$$
DELIMITER ;

调用: 

call new_procedure(1, @test);  --IN 参数直接传值1, out传变量@test
select @test;  --获取存储过程输出结果


example from github: 

/* assign some INOUT variables */
SET @x = 2;

/* call procedure and assign variables to OUT or INOUT positions */
CALL procedureName( "IN_VALUE_HERE", @x, @y, ... );

/* get them */
SELECT @x AS whatever_name_you_want, @y AS who_cares;

ref: https://github.com/mysqljs/mysql/issues/407 

原文地址:https://www.cnblogs.com/buxizhizhoum/p/7722616.html