• mysql存储过程


    在一些语言中,有一个概念叫“过程”procedure和“函数”function。  在PHP中,没有过程只有函数。

    过程:封装了若干条sql语句,调用时这些封装体执行。          函数:是一个有返回值的“过程”    (过程,没有返回值的函数)

    一、存储语法

    1. >create procedure procedureName()    //创建过程p1
    2. >begin
    3. >--sql语句体                //例如:select 2+3 from dual;
    4. >end$
    5. 查看过程:>show procedure statusG
    6. 调用procedure方法:>call procedure()$     //例如:call p1()$ 
    • 存储过程是可以编程的,意味着可以使用变量/表达式/控制结构,来完成复杂的功能。  在存储过程中,用declare声明变量
    • 格式:declare 变量名 变量类型 [default 默认值]

    声明一个变量过程例子:

    1. >create procedure p2()
    2. >begin
    3. >declare age int default 18;
    4. >declare height int default 180;
    5. >select concat('年龄是:',age,'身高是:',height);
    6. >end$ 
    • 存储过程中,变量可以sql语句中合法的运算。注意的是,如何把运算结果赋值给变量
    • 格式:set 变量名 :=expression

    例子1:

    1. >create procedure p3()
    2. >begin
    3. >declare age int default 18;
    4. >set age :=age+20;     //20年后
    5. >select concat('20年后的年龄是:',age);
    6. >end$ 

    例子2:

    1. >delimiter $ create procedure p4() begin declare age int default 28; 
    2. >if age>=18 then select '已成年';
    3. >else select '未成年';
    4. >end if;
    5. >end$

    二、存储过程的参数传递

    • 存储过程的括弧里可以声明参数
    • 语法:[in/out/inout] 参数名 参数类型

    例子:create procedure p5(width int, height int)

        begin 

          select concat('你的面积是',width*height) as area;

          if width>height then select '你挺胖';

          elseif width <height select '你挺瘦';

          else select '你挺方';

          end if;

        end$

    执行后可以测试传参:call p5(2,5)     输出:area:10, '你挺瘦'

    • 控制结构:顺序/选择/循环

    while语法:while 条件 do 循环体 end while; 

    例子:求1-100的和。

    1. create procedure p6() begin
    2. declare total  int default 0;declare num int default 0;
    3. while num<=100 do
    4. set num :=num+1;    set total :=total+num;
    5. end while;
    6. select total;
    7. end$

        

  • 相关阅读:
    自建mail服务器之一:dns解析
    区间树
    3d tech
    3d
    平板比较
    Node。js 访问gmail
    node nightmare 网页自动化测试 sample
    node start
    中國駐香港外交部
    create a simple COM object
  • 原文地址:https://www.cnblogs.com/step-city/p/5766018.html
Copyright © 2020-2023  润新知