当前位置:Gxlcms > 数据库问题 > 第13章 MySQL高级编程

第13章 MySQL高级编程

时间:2021-07-01 10:21:17 帮助过:1人阅读

procedure example delimiter // # 分隔符//替换; 使得在存储过程中使用分号分隔符 create procedure total_orders (out total float) # total_orders是存储过程名称 # out表示该参数将被传出或返回(对应的是in) # total是被传递的参数,若有多个参数则用逗号分隔 # float是参数的类型 BEGIN select sum(amount) into total from orders; END // delimiter; # 过程声明完成,将分隔符重新设置为分号

    过程声明结束后,使用call关键字:

             如: call total_orders(@t);

                     //调用total_orders过程并传入一个用来保存结果的变量@t

                     //查看结果: select @t;

②声明一个存储函数:

# basic_function.sql
# Basic syntax to create a function
delimiter //

create function add_tax (price float) returns float
begin
    declare tax float default 0.10; 
    # declare用于在begin...end中声明局部变量
    return price*(1+tax);
end
//

delimiter;

        查看结果: select add_tax(100); //100是传过去的price值

③查看定义存储过程和存储函数:

            show create procedure total_orders;

            show create function add_tax;

    删除之:

            drop procedure total_orders;

            drop function add_tax;

④游标、控制结构:

# control_structures_cursors.sql

# Procedure to find the orderid with the largest amount
# could be done with max, but just to illustrate stored procedure principles
delimiter //

create procedure largest_order(out largest_id int)
begin
    declare this_id int;  #当前行的orderid值
    declare this_amount float;  #当前行的amount值
    declare l_amount float default 0.0;  #最大的订单金额
    declare l_id int;  #最大订单金额对应的ID

    declare done int default 0;  #循环标记
    # 声明句柄,类似于存储过程中的一个异常
    #(该句柄将在sqlstate 02000语句被执行时调用)
    declare continue handler for sqlstate 02000 set done =1;
    # 游标c1,类似于一个数组从一个查询获得结果集
    declare c1 cursor for select orderid, amount from orders;  

    open c1;  #open才是真正开始执行查询
    repeat
        fetch c1 into this_id, this_amount;
        if not done then
            if this_amount>l_amount then
                set l_amount=this_amount;
                set l_id=this_id;
            end if;
        end if;
    until done end repeat;
    close c1;

    set largest_id=l_id;
end
//

delimiter;

           调用过程: call largest_order(@l);

           查看结果: select @l;

第13章 MySQL高级编程

标签:

人气教程排行