7 MySQL存储过程和函数

目录:

1. 存储过程和函数概述
2. 准备工作
3. 存储过程操作
4. 创建带参存储过程
5. 查看存储过程

 

1. 存储过程和函数概述

  MySQL的存储过程(stored procedure)和函数(stored function)统称为stored routines。
  存储过程和函数都是事先经过编译并存储在数据库中的一段SQL语句的集合,调用存储过程和函数可以简化应用开发人员的很多工作,减少数据在数据库和应用服务器之间的传输。
  存储过程和函数的区别在于函数必须有返回值,而存储过程没有,存储过程的参数可以使用IN、OUT、INOUT类型,而函数的参数只能是IN类型。

2. 准备工作(为了提高没小节的独立性,该准备工作会在后续指导中反复用到)

  创建表,掺入数据

  

 1 drop table if exists student;
 2 
 3 create table student (
 4 id int(5) not null,
 5 name varchar(20),
 6 birthday date
 7 );
 8 
 9 insert into student values(1, 'guo jing', '1990-01-01');
10 insert into student values(2, 'huang rong', '1992-02-02');
11 insert into student values(3, 'ling hu', '1993-03-03');
12 insert into student values(4, 'dong fang', '1994-04-04');
View Code

3. 存储过程操作

  3.1 创建存储过程

  选择schoolDB数据库,并在SQL编辑中输入如下代码:
create procedure get_young()
begin
select * from student where birthday in (select max(birthday) from student);
end//

(注意更改delimiter为 //)

  

  3.2查看存储过程
show procedure status;

   

  
  
  3.3 在SQL编辑框中调用存储过程

call get_young();
(注意:返回错误,目前不清楚如何更改,但经试验,在MySql Command Line Client中可以成功调用该存储过程。)

  
  3.4 使用MySql Command Line Client调用存储过程

  点击win7左下开始项,在搜索框中输入mysql,点击进入MySql Command Line Client。

  call get_young();
  调用成功。


但在 MySql Command Line Client 中创建存储过程中需注意,因为MySql Command Line Client中需要用语句更改delimiter,mysql中默写分界符是; ,但select 语句末有;冲突,需要修改分界符。
delimiter //
create procedure get_old()
begin
select * from student where birthday in (select min(birthday) from student);
end//
delimiter ;

   


4. 创建带参存储过程

在MySQL命令行中输入
delimiter //
create procedure get_by_year(IN year_in varchar(4))
begin
select * from student where year(birthday)=year_in;
end //
delimiter ;
调用该存储过程
call get_by_year();
返回错误,提示需要带入参数。

  
call get_by_year(1990);
调用成功!

   

5. 查看存储过程

show procedure status;

  
6. 删除存储过程

drop procedure get_old;

原文地址:https://www.cnblogs.com/kereturn/p/4147458.html