SQL 中存储过程怎么使用?

如题所述

一、简单的储存过程:

1、创建一个存储过程

create procedure GetUsers()

begin 

select * from user; 

end;12345

2、调用存储过程

call GetUsers();12

3、删除存储过程

drop procedure if exists GetUsers;

二、带参数的存储过程

1、MySql 支持 IN (传递给存储过程) , OUT (从存储过程传出) 和 INOUT (对存储过程传入和传出) 类型的参数 , 存储过程的代码位于 BEGIN 和 END 语句内 , 它们是一系列 SQL 语句 , 用来检索值 , 然后保存到相应的变量 (通过指定INTO关键字) ;

2、下面的存储过程接受三个参数 , 分别用于获取用户表的最小 , 平均 , 最大分数 , 每个参数必须具有指定的类型 , 这里使用十进制值(decimal(8,2)) , 关键字 OUT 指出相应的参数用来从存储过程传出

create procedure GetScores(

out minScore decimal(8,2),

out avgScore decimal(8,2),

out maxScore decimal(8,2)

)

begin

select min(score) into minScore from user;

select avg(score) into avgScore from user;

select max(score) into maxScore from user;

end;1234567891011

3、调用此存储过程 , 必须指定3个变量名(所有 MySql 变量都必须以 @ 开始) , 如下所示 :

call GetScores(@minScore, @avgScore, @maxScore);12

4、该调用并没有任何输出 , 只是把调用的结果赋给了调用时传入的变量 @minScore, @avgScore, @maxScore , 然后即可调用显示该变量的值 :

select @minScore, @avgScore, @maxScore;

5、使用 IN 参数 , 输入一个用户 id , 返回该用户的名字 :

create procedure GetNameByID(

in userID int,

out userName varchar(200)

)

begin

select name from user

where id = userID

into userName;

end;12345678910

6、调用存储过程 :

call GetNameByID(1, @userName);

select @userName;123

参考资料

SQL存储过程使用介绍.csdn博客[引用时间2017-12-31]

温馨提示:答案为网友推荐,仅供参考
相似回答