mysql 存储过程

创建存储过程film_in_stock:
mysql> DELIMITER $$
mysql>
mysql> CREATE PROCEDURE film_in_stock(IN p_film_id INT, IN p_store_id INT, OUT p_film_count INT)
    -> READS SQL DATA
    -> BEGIN
    ->   SELECT inventory_id
    ->   FROM inventory
    ->   WHERE film_id = p_film_id
    ->   AND store_id = p_store_id
    ->   AND inventory_in_stock(inventory_id);
    ->
    ->   SELECT FOUND_ROWS() INTO p_film_count;
    -> END $$
  Query OK, 0 rows affected (0.00 sec)
mysql>
mysql> DELIMITER ;

执行存储过程mysql>call  film_in_stock(1,2,@a);

                 mysql>select @a;

通常我们在执行创建过程和函数之前,都会通过“DELIMITER $$”命令将语句的结束符从“;”修改成其他符号,这里使用的是“$$”,这样在过程和函数中的“;”就不会被MySQL 解释
成语句的结束而提示错误。在存储过程或者函数创建完毕,通过“DELIMITER ;”命令再将结束符改回成“;”。

删除存储过程 mysql>drop procedure film_in_stock;

查看存储过程状态 mysql> show procedure status like 'film_in_stock' \G;

查看存储过程定义 mysql> show create procedure film_in_stock \G;

 

创建光标的存储过程

mysql> delimiter $$
mysql>
mysql> CREATE PROCEDURE payment_stat ()
-> BEGIN
->   DECLARE i_staff_id int;
->   DECLARE d_amount decimal(5,2);
->   DECLARE cur_payment cursor for select staff_id,amount from payment;
->   DECLARE EXIT HANDLER FOR NOT FOUND CLOSE cur_payment;
->
->   set @x1 = 0;
->   set @x2 = 0;
->
->   OPEN cur_payment;
->
->   REPEAT
->   FETCH cur_payment INTO i_staff_id, d_amount;
->   if i_staff_id = 2 then
->   set @x1 = @x1 + d_amount;
->   else
->   set @x2 = @x2 + d_amount;
->   end if;
->   UNTIL 0 END REPEAT;
->
->   CLOSE cur_payment;
->
-> END;
-> $$


mysql> delimiter ;

 

mysql> select @x1,@x2;
+----------+----------+
| @x1     | @x2        |
+----------+----------+
| 33927.04 | 33489.47 |
+----------+----------+
1 row in set (0.00 sec)

 

posted @ 2017-04-18 20:14  夏天的西瓜君  阅读(456)  评论(0编辑  收藏  举报