為了演示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|
可以發現言承旭的到來拉低了班級的平均分數。