时间:2021-07-01 10:21:17 帮助过:1人阅读
过程声明结束后,使用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高级编程
标签: