11)-MySQL存储过程

创建存储过程


create procedure productpricing()   #定义存储过程函数名称
begin   #存储开始
   select avg(prod_price) as priceaverage   
   from products;    #MySQL语句
end;  #结束
 
shell模式下执行mysql语句注意:分隔符

  delimiter //
   create procedure productpricing()
   begin
      select avg(prod_price) as priceaverage
      from products;
   end //
   delimiter ;
 
DELIMITER//告诉命令行实用程序使用//作为新的语句结束分隔符
可以看到标志存储过程结束的END定义为END//而不是END;
这样,存储过程体内的;仍然保持不动,并且正确地传递给数据库引擎。
最后,为恢复为原来的语句分隔符,可使用DELIMITER;。
 
调取存储过程

 call avg_student()  #通过关键词call调取存储过程名称  
 
# 因为存储过程实际上是一种函数,所以存储过程名后需要有()符号(即使不传递参数也需要)。

删除存储过程


 drop procedure productpricing;  
 
这条语句删除刚创建的存储过程。请注意没有使用后面的(),只给出存储过程名。

检查存储过程

show create procedure ordertotal;
 
存储过程例子(1)

create procedure ordertotal(
   in onumber int,          #in 用来接收用户输入
   out ototal decimal(8,2)  #out用来返回用户输入
)
begin
   select sum(item_price*quantity)
   from orderitems
   where order_num = onumber
   into ototal;             #into用来接收值
end;
 
调取

CALL ordertotal(20005, @total);
 
存储过程例子(2)
 
create procedure ordertotal(
   in onumber int,           #接收用户值
   in taxable boolean,
   out ototal decimal(8,2)   #返回值
)
begin
   declare total decimal(8,2);     #定义局部变量
   declare taxrate int default 6;   #定义局部变量
   select sum(item_price*quantity)
   from orderitems
   where order_num = onumber
   into total;     #存储值
   if taxable then    #if判断
      select total+(total/100*taxrate) into total;
   end if;
   select total into ototal;
end;
 
调取

call ordertotal(20005, 0, @total);
select @total;
posted @ 2018-12-14 10:55  奢华使命  阅读(183)  评论(0编辑  收藏  举报