码迷,mamicode.com
首页 > 其他好文 > 详细

procrdure存储过程

时间:2016-06-19 22:36:51      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:

/*
存储过程

在一些语言中,有一个概念叫”过程“ procedure,和”函数“ function

过程:封装了若干条语句,调用时,这些封装体执行
函数:是一个有返回值的“过程”
过程:没有返回值的函数

我们把若干条sql封装起来,起个名字---过程
把此过程存储在数据库中---存储过程

*/

-- 创建一个简单的存储过程
create procedure p1()
begin
select 1+2 ;
end;

--查看已有的procedure
show procedure status;

--调用存储过程
call p1();

--存储过程引入变量和控制结构
/*
存储过程是可以编程的
意味着可以使用变量,表达式,控制结构来完成复杂的操作
在存储过程中使用declare声明变量
    格式 declare 变量名 变量类型 [default 默认值]
只是简单的声明输出变量值不能满足我们的要求,我们喜欢用变量做一些运算,如:+*-/
运算的结果,如何复制给变量呢?
    set 变量名 := exp
    
控制结构:
     if/else语句:格式:
             if  condition then
             statement
             else
             statement
             end if;
     if/elseif/else语句:格式:
             if condition then
             statement
             elseif condition then
             statement
             ...
             end if;
             
--给存储过程传参
存储过程的括号里,可以声明参数
    语法是: [in/out/inout] 参数名 参数类型
*/

--使用变量的存储过程
create procedure p2()
begin
declare height int default 180;
declare age int default 18;
select concat(年龄,age,身高,height);
end;

call p2();

--加入运算
create procedure p3()
begin
declare age int default 18;
set age=age+20;
select concat(20年后这么大了:,age);
end;

call p3();

--加入控制语句
create procedure p4()
begin
declare age int default 18;
set age=age+20;
if age<12 then
select 未成年;
else 
select 成年人;
end if;
end;

call p4();

--使用简单的参数
create procedure p5(width int,height int) -- 求面积
begin
     select concat(你的面积是,width*height) as area;
     
     if width>height then
     select 你很胖;
     elseif width<height then
     select 你很瘦;
     else
     select 你挺方;
     end if;
end;

call p5(4,5);

/*
循环语句
while循环
*/
create procedure p6()
begin
declare total int default 0;
declare num int default 0;

while num<100 do
set total :=total+num;
set num :=num+1;
end while;

select total;
end;

call p6();
--1~n的和
create procedure p7(num int)
begin
declare total int default 0;

while num>0 do
set total :=total+num;
set num :=num-1;
end while;

select total;
end;
call p7(3);

 

procrdure存储过程

标签:

原文地址:http://www.cnblogs.com/aigeileshei/p/5598945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!