存储过程

存储过程是一组为了完成某项特定功能的SQL语句集,其实质就是一段存储在数据库中的代码.它可以由声明式的sql语句和过程式sql语句组成.

优点:可增强SQL语言的功能和灵活性,良好的封装性,高性能,可减少网络流量,可作为一种安全机制来确保数据库的安全性和数据的完整性.

mysql-> use mysql_test;

mysql-> delimiter $$ 

    -> create procedure sp_update_sex(in cid int,in csex char(2))

    -> begin  

    -> update cust set cust_sex=csex where cust_id=cid;

    -> end $$

mysql-> call sp_update_sex(909,'M')$$   //调用存储过程

mysql-> select * from cust $$   

mysql-> drop procedure sp_update_sex$$   //删除存储过程

mysql-> call sp_update_sex(909,'M')$$     //报错 procedure mysql_test.sp_update_sex does not exist

存储过程体

使用declare语句声明局部变量

declare var_name[...] type[default value]

declare cid int(10);

1)只能在存储过程体的begin...end语句块中声明;

2)必须在存储过程的开头处声明;

3)作用范围仅限于声明它的begin...end语句块;

4)不同于用户变量

局部变量和用户变量的区别

1)局部变量声明时,在其前面没有@符号,并且它只能被声明它的begin...end语句块中的语句所使用.

2)用户变量在声明时,会在其名称前面使用@符号,同时已声明的用户变量存在于整个会话之中.

使用set语句为局部变量赋值

set var_name=expr[,var_name=expr]...

set cid=910;

使用select...into语句把选定列的值直接存储在局部变量中

select col_name[,...] into var_name[,...] table_expr

流程控制语句  

1)条件判断语句

if...then...else语句

  if 条件 then

    表达式1

  else

    表达式2

  end if;

case语句

2)循环语句     \ iterate 用于表示退出当前循环

while语句

  while 条件

    表达式

  end while

repeat语句

  repeat

    表达式

  end repeat

loop语句

  loop

    表达式

  end loop

使用declare cursor语句创建游标

declare cursor_name cursor for select_statement

使用open语句打开游标

open cursor_name

使用fetch...into语句读取数据

fetch cursor_name into var_name[,var_name]...

使用close语句关闭游标

close cursor_name

原文地址:https://www.cnblogs.com/lsxsx/p/13389919.html