存储过程入门

我们常用的操作数据库语言SQL语句在执行的时候需要要先编译,然后执行,而存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中,用户通过指定存储过程的名字并给定参数(如果该存储过程带有参数)来调用执行它。

一个存储过程是一个可编程的函数,它在数据库中创建并保存。它可以有SQL语句和一些特殊的控制结构组成。当希望在不同的应用程序或平台上执行相同的函数,或者封装特定功能时,存储过程是非常有用的。数据库中的存储过程可以看做是对编程中面向对象方法的模拟。它允许控制数据的访问方式。

简单来说就是存储过程就是将若干条sql语句封装起来,编译好放在mysql服务器中,需要时调用即可

存储过程的创建语法

 

create procedure procedureName()
begin
    //sql语句
end

存储过程是可以编程的,意味着可以使用变量、表达式、控制结构,来完成复杂的功能

1.在存储过程中,使用declare声明变量,其格式为:declare 变量名 变量类型 [default 默认值]

例如:

create procedure p1()
begin
    declare age int default 18;
    declare height int default 180;
    select concat('年龄',age,'身高是',height);
end

 2.存储过程中,变量可以使用sql语句进行合法的运算,如+、-、*、/

  运算结果赋值给变量: set 变量名 := expression(表达式)

create procedure p2()
begin
    declare age int default 18;
    set age := age + 20;
    select concat('20年后年龄是',age);
end

 3.控制结构,与我们平常见到的if、else差不多

create procedure p3()
begin
	declare age int default 18;
	if age > 18 then
		select '已成年';
	else 
		select '未成年';
	end if;
end

4.循环结构(while和repeat)

//循环结构
create procedure p4()
begin
    declare num int default 0;
    declare total int default 0;

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

    select total;
end$

create procedure p5()
begin
    declare i int default 0;
    declare total int default 0;

    repeat
    set i := i + 1;
    set total := total + i;
    until i >= 100 end repeat;

    select total;
end$

5.case结构(类似java的switch)

create procedure p6()
begin
    declare pos int default 0;

    set pos := floor(5*rand());

    case pos
    when 1 then select '还在飞';
    when 2 then select '掉海里了';
    when 3 then select '在小岛上';
    else select '我不知道';
    end case;
end$

 

转载于:https://www.cnblogs.com/lzxl/p/4117804.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值