MySQL Crash Course #15# Chapter 23. Working with Stored Procedures

以前写过类似的东西,用来自动生成数据。

你可以将 Stored Procedure 理解为可以重复使用的批处理文件。

Stored Procedure 非常有用,我们应该尽可能地去使用它。

那么,应用 Stored Procedure 有什么好处呢?

  • 封装过程,简化复杂的操作
  • 代码重用、共用,所有人都用同一个存储过程,减少出错的可能
  • 简化变更管理,如果业务逻辑发生改变,修改存储过程就可以了,上层软件甚至不需要知道发生了什么改变。
  • 提高性能,存储过程比单条执行要快
  • MySQL 语言让存储过程更加强大和灵活

查看已存在的存储过程(这个结果是可以过滤的!):

SHOW PROCEDURE STATUS;
SHOW CREATE PROCEDURE procedure_name;

调用一个已经存在的存储过程非常简单:

CALL productpricing(@pricelow,
                    @pricehigh,
                    @priceaverage);

但是写起来就没那么简单了,首先看一个简单的例子:

CREATE PROCEDURE productpricing()
BEGIN
   SELECT Avg(prod_price) AS priceaverage
   FROM products;
END;

This example creates a stored procedure called productpricing(), throw it on the command line and run it:

mysql> CREATE PROCEDURE productpricing()
    -> BEGIN
    ->    SELECT Avg(prod_price) AS priceaverage
    ->    FROM products;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4

The creation failed due to the delimiter, the solution is to temporarily change the delimiter:

DELIMITER //

CREATE PROCEDURE productpricing()
BEGIN
   SELECT Avg(prod_price) AS priceaverage
   FROM products;
END //

DELIMITER ;

Throw it in again and run, and then call the newly created stored procedure:

mysql> CALL productpricing();
+--------------+
| priceaverage |
+--------------+
|    16.133571 |
+--------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

 Remove this stored procedure:

DROP PROCEDURE IF EXISTS productpricing;

Create and call an upgraded version of the stored procedure:

DELIMITER //

CREATE PROCEDURE productpricing(
   OUT pl DECIMAL(8,2),
   OUT ph DECIMAL(8,2),
   OUT pa DECIMAL(8,2)
)
BEGIN
   SELECT Min(prod_price)
   INTO pl
   FROM products;
   SELECT Max(prod_price)
   INTO ph
   FROM products;
   SELECT Avg(prod_price)
   INTO pa
   FROM products;
END //

DELIMITER ;
mysql> CALL productpricing(@pricelow,
    ->                     @pricehigh,
    ->                     @priceaverage);
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> SELECT @pricelow, @pricehigh, @priceaverage;
+-----------+------------+---------------+
| @pricelow | @pricehigh | @priceaverage |
+-----------+------------+---------------+
|      2.50 |      55.00 |         16.13 |
+-----------+------------+---------------+
1 row in set (0.00 sec)

As you can see above, MySQL variable names must start with @. The variable types allowed by MySQL are the same as the field types allowed in the table. For stored procedure parameters, they can be divided into three categories: IN parameters, OUT parameters and INOUT parameters. Let’s look at a simple example again and create the following stored procedure :

DELIMITER //

CREATE PROCEDURE ordertotal(
   IN onumber INT,
   OUT total DECIMAL ( 8 , 2 )
)
BEGIN
   SELECT Sum(item_price*quantity)
   FROM orderitems
   WHERE order_num = onumber
   INTO ototal;
END // 

DELIMITER ;

View the total price of the order with id 20006:

mysql> CALL ordertotal(20006, @total);
Query OK, 1 row affected (0.00 sec)

mysql> SELECT @total
    -> ;
+--------+
| @total |
+--------+
|  55.00 |
+--------+
1 row in set (0.00 sec)

I have always felt that the translation of stored procedure is ambiguous, and it may be easier to understand if it is changed to "stored procedure". . .

Let's create a smarter stored procedure, which is what a stored procedure is really for:

-- Name: ordertotal
-- Parameters: onumber = order number
--             taxable = 0 if not taxable, 1 if taxable
--             ototal = order total variable

CREATE PROCEDURE ordertotal(
   IN onumber INT,
   IN taxable BOOLEAN,
   OUT total DECIMAL ( 8 , 2 )
) COMMENT 'Obtain order total, optionally adding tax'
BEGIN

   -- Declare variable for total
   DECLARE total DECIMAL(8,2);
   -- Declare tax percentage
   DECLARE taxrate INT DEFAULT 6;

   -- Get the order total
   SELECT Sum(item_price*quantity)
   FROM orderitems
   WHERE order_num = onumber
   INTO total;

   -- Is this taxable?
   IF taxable THEN
      -- Yes, so add taxrate to the total
      SELECT total+(total/100*taxrate) INTO total;
   END IF;

   -- And finally, save to out variable
   SELECT total INTO ototal;

END;

 

It is better for the upper-level program to do this work, or the database to do it? - - - - pending upgrade

 

For more details, please refer to the official documentation https://dev.mysql.com/doc/search/?d=201&p=1&q=stored+procedure

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324630251&siteId=291194637