SQL的存储过程

SQL也是一门编程语言
存储过程的定义:存储过程是封装了若干条语句存储在数据库中,调用时,这些封装体执行。

基本语法

//创建存储过程的语法:
create procedure procName()
begin
	--sql语句块
end;
//调用存储过程:
call procName();
//查看存储过程
show procedure status;
--或
select name from mysql.proc where db='数据库名' and type="PROCEDURE";
//删除存储过程
drop procedure procName();

存储过程是可以编程的,意味着可以使用变量、表达式、控制结构…来完成复杂的功能。
在存储过程中,使用declare声明变量
格式:declare 变量名 变量类型 [default 默认值]

//eg:
create procedure p1()
begin
	declare age int default 16;
	declare height int default 180;
	select concat("年龄是:", age, "身高是:", height);
end;

call p1();
/*result:
+-------------------------------------------+
| concat("年龄是:", age, "身高是:", height) |
+-------------------------------------------+
| 年龄是:16身高是:180                       |
+-------------------------------------------+
*/

存储过程中,变量可以在sql语句中合法运算,比如 + - * /
赋值格式:set 变量:=expression;

//eg:
create procedure p2()
begin
	declare num int default 1;
	set num:= num+1;
	select concat("1+1=" ,  num);
end;
call p2();
/*result:
+-----------------------+
| concat("1+1=" ,  num) |
+-----------------------+
| 1+1=2                 |
+-----------------------+
*/

给存储过程传参

三种类型的参数:in out inout
in:输入参数
out:输出参数;在存储过程外面可以访问参数,变成一个全局变量
inout:输入输出参数

控制结构

//if/else结构
create procedure p3()
begin
	declare num int default 2;
	if num > 1 then
		select "正确" as a;
	else
		select "错误" as a;
	end if;
end;
//while结构;求1~n之和;in/out实例
create procedure p4(in n intout total int)
begin
	declare num int default 0;
	set total int default 0;
	
	while num <=n do
		set total:=total+num;
		set num:=num+1;
	end while;
end;

call p5(50,@sumary);
select @sumary; //显示全局变量
/*
+---------+
| @sumary |
+---------+
|    1275 |
+---------+
*/

//case结构
create procedure p6()
begin
  declare pos int default 0;
  set pos:=floor(rand()*5); //产生0~5的随机整数
 
  case pos
  when 1 then select '一' as a;
  when 2 then select '二' as a;
  when 3 then select '三' as a;
  else select '其他' as a;
  end case;
end;

//repeat 循环结构
create procedure p7()
begin
	declare i int default 0;
	
	repeat
		select i;
		set i:=i+1;
		until i>5 end repeat;
end;
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值