超详细讲解mysql存储过程当中的in/out/inout

存储过程

大概定义:用一个别名来描述多个sql语句的执行过程。sql

  • 最简单
    delimiter //
    create PROCEDURE p1()
    begin
    select * from userinfo;
    end //
    delimiter ;
    
    call p1();
  • 传参(in, out, inout)
    • in 表示传入的参数, 能够传入数值或者变量,即便传入变量,并不会更改变量的值,能够内部更改,仅仅做用在函数范围内。session

      delimiter //
      create procedure p2(
          in v1 int
          )
          begin
          set v1 = 2 * v1;
          select v1;
          end //
      
      delimiter ;
      
      call p2(19);
      
      ----------------
      delimiter //
      create procedure p6(
          in v int
          )
          begin 
          set v = 10;
          select v;
          end //
      delimiter ;
      
      call p6(10);
      
      set @v4 = 0;
      call p6(@v4);
      select @v4;  -- 此时@v4依然为0
    • out 表示存储执行存储过程的返回结果,且参数只能是一个变量,且只能对其赋值(函数执行完之后也生效),不能在函数内获取其值。函数

      delimiter //
      create procedure p3(
          out v int
          )
          begin
          set v = 10;
          end //
      delimiter ;
      
      set @v1 = 0; # @varible_name 相似于定义一个局部变量,跟session同样
      call p3(@v1); 
      select @v1;
      
      -----------------------------
      delimiter //
      create procedure p4(
          out v int
          )
          begin 
          set v = v + 5;  -- 这儿有问题,不能这样,只能直接赋值
          select v;
          end //
      delimiter ;
      -- 这段代码是有问题的。
      delimiter //
      create procedure p5(
          out v int
          )
          begin 
          set v = 5; -- 对的
          select v;
          end //
      delimiter ;
      
      set @v3 = 0;
      call p5(@v3);
    • inout 表示从外部传入的参数通过修改后能够返回的变量,既能够使用传入变量的值也能够修改变量的值(即便函数执行完)。code

      delimiter //
      create procedure p7(
          inout v int
          )
          begin
          set v = 9999;
          select v;
          end //
      delimiter ;
      
      call p7(10);
      
      set @v5 = 0;
      call p7(@v5);
      select @v5;
      
      ------------------------------------
      
      delimiter //
      create procedure p8(
          inout v int
          )
          begin
          set v = v + 9999;
          select v;
          end //
      delimiter ;
      
      set @v6 = 1;
      call p8(@v6);
      select @v6;

综上

  • in只能够读取值/变量,不能更改
  • out不能读,能够更改
  • inout既能够读又能够更改
相关文章
相关标签/搜索