Table of Contents
4. Use stored procedures
4. Delete the stored procedure
5. Use parameters
6. Establishing intelligent stored procedures
7. Check the stored procedure
Home Database Mysql Tutorial Detailed introduction to mysql stored procedures (code example)

Detailed introduction to mysql stored procedures (code example)

Feb 27, 2019 pm 01:42 PM
mysql stored procedure

This article brings you a detailed introduction (code example) about mysql stored procedures. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is a stored procedure?

A collection of one or more MySQL statements saved for later use.

The concept of stored procedures is code encapsulation and reuse at the SQL language level of the database.

(Related recommendations: MySQL Tutorial)

2. Why use stored procedures

  1. Encapsulate processing in easy-to-use units, simplifying complex operations

  2. Prevent errors and ensure data consistency

  3. Simplify the response to changes manage. (Modify the corresponding table name, column name, etc. to modify the code of the corresponding stored procedure. People who use it do not need to know the changes)

  4. Improve performance

  5. flexible

In general, it is simple, safe and high-performance
Disadvantages:

  1. It is more complicated to write than SQL statements

  2. Permission problem (may not have permission, generally use stored procedures, do not have permission to create stored procedures)

3. Create stored procedures

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

Note: Problems entered in the command line

mysql> delimiter //
mysql> CREATE PROCEDURE productpricing()
    -> BEGIN
    -> SELECT Avg(prod_price) AS priceaverage
    -> FROM products;
    -> END //
Copy after login

4. Use stored procedures

The stored procedure is actually a function

CALL productpricing();
Copy after login

4. Delete the stored procedure

    drop procedure productpricing;
    drop procedure if EXISTS productpricing;
Copy after login

5. Use parameters

Generally, the stored procedure does not display the results, but returns the results to the variable you specify
Variable (variable) A specific location in memory used to temporarily store data.

CREATE PROCEDURE productpricing(
    OUT p1 DECIMAL(8,2),
    OUT ph DECIMAL(8,2),
    OUT pa DECIMAL(8,2)
)
BEGIN
SELECT MIN(prod_price)
INTO p1
FROM products;
SELECT MAX(prod_price)
INTO ph
FROM products;
SELECT avg(prod_price)
INTO pa
FROM products;
END;
Copy after login

The keyword OUT indicates that the corresponding parameter is used to pass a value from the stored procedure (returned to the caller).
MySQL supports IN (passed to stored procedures),
OUT (passed from stored procedures, as used here)
INOUT (passed in and out of stored procedures) type parameters.

Variable name All MySQL variables must start with @.
Call stored procedure

call productpricing(@pricelow,@pricehign,@priceaverage);
Copy after login

Query

SELECT @priceaverage;
Copy after login
SELECT @priceaverage,@pricehign,@pricelow;
Copy after login

Use in and out
Create

CREATE PROCEDURE ordertotal(
    IN onumber INT,
    OUT ototal DECIMAL(8,2)
)
BEGIN
SELECT sum(item_price*quantity)
FROM orderitems
WHERE order_num = onumber
INTO ototal;
END;
Copy after login

Calling

call ordertotal(20005,@total);
Copy after login

Query

select @total;
Copy after login

6. Establishing intelligent stored procedures

All stored procedures used so far are basically encapsulated MySQL simple SELECT statements. Although they are all valid examples of stored procedures, they can do what you can directly use these encapsulated statements (if they can bring anything more, it is to make things more complicated). The power of stored procedures truly becomes apparent only when they include business rules and intelligent processing within them.

   考虑这个场景。你需要获得与以前一样的订单合计,但需要对合计增加营业税,不过只针对某些顾客(或许是你所在州中那些顾客)。那么,你需要做下面几件事情:
   1、获得合计(和以前一样)
   2、把营业税有条件的添加到合计
   3、返回合计(带或不带税的)
Copy after login

We enter the following code:

-- Name: ordertotal        //   添加注释
-- Parameters: onumber = order number
--             taxable = 0 if not taxable, 1 if taxtable
--             ototal = order total variable

CREATE     PROCEDURE ordertotal (
IN onumber INT,
IN taxable BOOLEAN,
OUT ototal 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;
Copy after login
此存储过程有很大的变动。首先,增加了注释(前面放置 --)。在存储过程复杂性增加时,这样做特别重要。  
添加了另外一个参数 taxable,它是一个布尔值(如果要增加税则为真,否则为假)。  
在存储过程体中,用 DECLARE语句定义了两个局部变量。 DECLARE要求指定变量名和数据类型,
它也支持可选的默认值(这个例子中的 taxrate的默认被设置为 6%)。SELECT 语句变,因此其结果存储到 total(局部变量)而不是 ototal。  
IF 语句检查taxable是否为真,如果为真,则用另一SELECT语句增加营业税到局部变量 total。

最后,用另一SELECT语句将total(它增加或许不增加营业税)保存到 ototal。  
注意:COMMENT关键字 ,本例子中的存储过程在 CREATE PROCEDURE语句中包含了一个 COMMENT值。  
它不是必需的,但如果给出,将在SHOW PROCEDURE STATUS的结果中显示。

这显然是一个更高级,功能更强的存储过程。为试验它,请用以下两条语句:  
第一条:
Copy after login
call ordertotal(20005, 0, @total);
SELECT @total;
Copy after login
输出:
Copy after login
Copy after login
+--------+
| @total |
+--------+
|  38.47 |
+--------+
Copy after login
第二条:
Copy after login
call ordertotal(20009, 1,@total);
SELECT @total;
Copy after login
输出:
Copy after login
Copy after login
+--------+
| @total |
+--------+
|  36.21 |
+--------+
Copy after login
BOOLEAN值指定为1 表示真,指定为 0表示假(实际上,非零值都考虑为真,只有 0被视为假)。通过给中间的参数指定 0或1 ,可以有条件地将营业税加到订单合计上。
Copy after login

This example gives the basic usage of MySQL's IF statement. The IF statement also supports ELSEIF and ELSE clauses (the former also uses the THEN clause, the latter does not). We will see other uses of IF (and other flow control statements) in future chapters.

7. Check the stored procedure

To display the CREATE statement used to create a stored procedure

show create PROCEDURE ordertotal;
Copy after login

To obtain detailed information about the stored procedure including when and by whom it was created. List

show procedure status;
Copy after login

There are many tables, use like to filter

show procedure status like 'ordertotal';
Copy after login

The above is the detailed content of Detailed introduction to mysql stored procedures (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL for Beginners: Getting Started with Database Management MySQL for Beginners: Getting Started with Database Management Apr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

See all articles