MySQL----存储过程

存储过程

  • 关键字 Procedure

  • 为了完成特定功能的SQL语句集,存储在数据库中,经过第一次编译后,再次调用不需要再次编译,用户只需要指定存储过程名字并给定参数就可以执行完成任务。

  • 最主要的还是执行效率和SQL 代码封装

    • SQL 代码封装功能
      • MySQL 存储过程将业务逻辑封装到存储过程中,便于维护,执行效率高。
  • 创建存储过程

    • create procedure 存储过程名([in][out][inout] 参数 datatype) 
      Begin
      	sql语句集
      	... ...
      end
      

    注:存储过程只是先编译sql语句,所以当sql语句中有错误的表或属性时,系统不会提示;而且存储过程会创建成功;只有当调用执行时才会提示错误

    例:

    • 第一步:修改结束符号

      Delimiter #

    • 第二步:创建存储过程

      create procedure p_a()
      	Begin
      		select*from t_student where sscore>500;
      		select*from t_dept;
      		select*from t_man;
      	end
      
    • 第三步:修改结束符号

      Delimiter #;

    • 第四步:调用存储过程 call

      Call p_a();

  • 删除存储过程

    Drop procedure if exists p_a;

  • 带参的存储过程

    Create procedure tat(n1 int,n2 int)
    	Begin
    		Declare n3 int;
    		if n1 is null than set n1=10;
    		end if;
    		Set n3 = n1+n2;
    		Select n3 as sum;
    	end		
    
  • 存储过程的参数分类:分为3类

    • In:表示需要给存储过程一个值(默认)

      create procedure p_c(in n1 int)
      	Begin
      		Select*from t_student where sid=n1;
          end
          
      call p_c(1227);
      
    • Out:表示存储过程会返回一个值

      • 存储过程没有return,但是有into
      create procedure p_d(out n2 int)
      	Begin
      		Select max(sscore) into n2 from t_student;
      	end
      
      call p_d(@t);    //@t全局变量
      select @t;
      
    • Inout:表示既可以传值进去,又可以带值出来

      //in、out
      create procedure p_e(in n1 int, out n2 int) 
      	Begin
      		select sscore into n2 from t_student where sid=n1;
      	end
      call p_e(1220,@i);
      select @i;
      //inout
      create procedure P_k(inout n1 int)
      	Begin
      		select sscore into n1 from t_student where sid=n1;
      	end
      set @g=1203;
      call p_k(@g);
      select @g;
      
  • 展示数据库中有哪些存储过程

    • 展示存储过程的名字

      select name from mysql.proc status where db='数据库名';
      select name from mysql.proc status where db='lianxi';
      
    • 展示存储过程的详细信息

      show procedure status where db='数据库名';
      show procedure status where db='lianxi';
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值