存储过程:procedure 概念类似于函数,就是把一段代码封装起来, 当要执行这一段代码的时候,可以通过调用该存储过程来实现, 在封装的语句体里面,可以用if/else,case,while等控制结构, 可以进行sql编程 查看现有的存储过程 show procedure status 删除存储过程 drop procedure 存储过程的名字 调用存储过程 call 存储过程名字(); ------------------------------------------------- delimiter $ 1.第一个存储过程,体会"封装sql" create procedure p1() begin select * from g; end$ call p1()$ +------+--------+-------------+ | g_id | g_name | g_inventory | +------+--------+-------------+ | 1 | 猪 | 20 | | 2 | 鸭 | 18 | | 3 | 羊 | 15 | | 4 | 牛 | 23 | +------+--------+-------------+ 2.第二个存储过程,体会"参数" create procedure p2(id int) begin select * from g where g_id<id; end$ call p2(3)$ +------+--------+-------------+ | g_id | g_name | g_inventory | +------+--------+-------------+ | 1 | 猪 | 20 | | 2 | 鸭 | 18 | +------+--------+-------------+ 3.第三个存储过程,体会"控制结构" create procedure p3(num int,j char(4)) begin if j="high" then select * from g where g_inventory>num; else select * from g where g_inventory<num; end if; end$ call p3(20,"high")$ +------+--------+-------------+ | g_id | g_name | g_inventory | +------+--------+-------------+ | 4 | 牛 | 23 | +------+--------+-------------+ call p3(20,"low")$ +------+--------+-------------+ | g_id | g_name | g_inventory | +------+--------+-------------+ | 2 | 鸭 | 18 | | 3 | 羊 | 15 | +------+--------+-------------+ 4.第四个存储过程,体会"循环" 计算1-n的和: create procedure p4(n smallint) begin declare i int; declare sum int; set i=1; set sum=0; while i<=n do set sum=sum+i; set i=i+1; end while; select sum; end$ call p4(100)$ +------+ | sum | +------+ | 5050 | +------+
原文地址:http://1154179272.blog.51cto.com/10217799/1653271