MySQL存储过程示例

Posted <・)))><<

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL存储过程示例相关的知识,希望对你有一定的参考价值。

为了演示mysql中的存储过程,我们先创建一些表和数据:

drop table if exists my_test_table;
create table my_test_table (
    id integer primary key not null AUTO_INCREMENT,
    name varchar(20),
    age integer,
    point double
);
insert into my_test_table (name,age,point) values 
    (‘刘德华‘,40,10.0),(‘周杰伦‘,30,20.0),(‘周星驰‘,20,40.0),(‘范晓萱‘,20,20.0),(‘陈绮贞‘,10,10.0),
    (‘朴树‘,30,12.0),(‘谢天笑‘,40,10.0),(‘谢春花‘,20,10.0),(‘房东的猫‘,50,100.0),(‘许巍‘,30,10.0);

然后创建一个空参数的存储过程:

delimiter //
create procedure test_procedure1()
begin 
    select avg(point) as pointaverage
    from my_test_table;
end //
delimiter ;

然后运行这个存储过程:

call test_procedure1()

可以看到结果如下:

pointaverage|
------------|
        24.2|

删除存储过程:

drop procedure test_procedure1

注:这一点好像和DB2不一样。因为我之前在DB2下编写过存储过程,DB2可以定义同名但是不同参数的存储过程,然后DB2删除存储过程的时候是要带参数的。

下面的示例是带3个输出参数的存储过程示例:

drop PROCEDURE if exists test_procedure;
delimiter //
create procedure test_procedure(
    OUT pl double,
    OUT ph double,
    out pa double
)
begin 
    select min(point) as pointlow
    into pl
    from my_test_table;
    select max(point) as pointhigh
    into ph
    from my_test_table;
    select avg(point) as pointaverage
    into pa
    from my_test_table;
end //
delimiter ;

但是发现报错了,报错信息如下:

 SQL 错误 [S1009]: Parameter pl is not registered as an output parameter

初步估计是因为变量是需要在调用存储过程之前定义的,所以先定义一下变量:

set @pointlow=0,@pointhigh=0,@pointaverage=0;

重新运行,发现还是报一样的错。
我暂时没有发现解决办法~~
但是我按照下面这条语句执行了一下,发现是可以的:

call test_procedure(?,?,?);

并且是有输出的:

1 |2  |3   |
--|---|----|
10|100|24.2|

所以我猜想存储过程在MySQL 8中有所改变。

下面的存储过程包含输入参数,每调用一次会往my_test_table表中插入一条数据:

drop PROCEDURE if exists test_procedure;
delimiter //
create procedure test_procedure(
    IN in_name varchar(20),
    IN in_age integer,
    IN in_point double,
    out pa double
)
begin 
    insert into my_test_table (name,age,point) values (in_name,in_age,in_point);
    select avg(point) as pointaverage
    into pa
    from my_test_table;
end //
delimiter ;

然后调用一下存储过程:

call test_procedure(‘言承旭‘,30,1.1,?);

输出如下:

1                 |
------------------|
22.099999999999998|

可以发现言承旭的到来拉低了班级的平均分数。



以上是关于MySQL存储过程示例的主要内容,如果未能解决你的问题,请参考以下文章

求调用存储过程C#的合法示例:MYSQL

MySQL存储过程示例

MySql触发器使用

java 调用mysql的存储过程(简单示例)

Java调用SQL Server的存储过程详解(转)

带游标的Mysql存储过程