zoukankan      html  css  js  c++  java
  • MySQL学习笔记(四)—存储过程

    一、概述

         存储过程是数据库定义的一些SQL语句的集合,然后直接调用这些存储过程和函数来执行已经定义好的SQL语句。存储过程可以避免开发人员重复的编写相同的SQL语句,而且存储过程是在MySql服务器中存储和执行的,可以减少客户端与服务器端的数据传输。

    1.优点

    (1)提供执行性能

        通常在客户端执行SQL命令时,在数据库有解析到编译这个前期准备过程。但是,存储过程是先完成了解析、编译的处理后保存在数据库中的,执行时能减轻数据库负担,提高执行性能。

    (2)可减轻网络负担

         使用存储过程后,复杂的数据库操作也可以在数据库服务器中完成,只要从应用程序传递给数据库必要的参数就行,比起多次传递SQL命令,这大大减轻了网路负担。

    二、基本操作

    1.定义存储过程

    #创建存储过程
    create procedure p1()
    begin 
    	select * from t_user;
    end

    2.调用存储过程

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

    3.查看存储过程

    #查看存储过程
    show procedure  status;

    4.删除存储过程

    #删除存储过程
    drop procedure p1;

    5.创建带参数的存储过程

    #1.创建带参数的存储过程
    create procedure p2(i int)
    begin 
    	select * from t_user where id > i;
    end
    
    #2.调用带参数的存储过程
    call p2(3);
    结果:

          image

    6.创建带判断语句的存储过程

    #1.创建带判断语句的存储过程
    create procedure p3(i int,j char(10))
    begin 
      if j = 'high' then 
        select * from t_user where id > i;
      elseif  j = 'low' then
    		select * from t_user where id < i;
      end if;
       
    end
    
    #2.调用带选择结构的存储过程
    call p3(3,'low');

    结果:

         image

    7.使用case命令使用多重条件语句

    #1.使用case命令多重条件分支
    create procedure p4(i int)
    begin 
         case i
         when 1 then 
    		 select * from t_user where address='北京';
    		 when 2 then 
    		 select * from t_user where address='上海';
    		 else 
    		 select * from t_user where address='吉林';
    		 end case;
    end
    #2.查看结果
    call p4(2);

    结果:

         image

    8.创建局部变量

    #1.创建局部变量
    create procedure p5(i int)
    begin 
    	declare temp varchar(10);
    	case i
      when 1 then 
    		set temp = '北京';
    	when 2 then 
    		set temp = '上海';
    	when 3 then 
    		set temp = '吉林';
    	end case;
    	select * from t_user where address= temp;
    end
    
    #2.查看结果
    call p5(3);

    结果:

          image

  • 相关阅读:
    分布式事务之可靠消息
    分布式事务之本地消息表
    分布式事务
    数据库之 事务
    WePY开发小程序(二):项目入口及注册页面、组件
    WePY开发小程序(一):入门
    vue学习笔记-事件监听
    vue学习笔记-列表渲染
    vue学习笔记-缩写
    vue学习笔记-常用指令
  • 原文地址:https://www.cnblogs.com/yangang2013/p/5693041.html
Copyright © 2011-2022 走看看