search
HomeDatabaseMysql TutorialDetailed introduction to mysql stored procedures (code example)

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

Note: Problems entered in the command line

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

4. Use stored procedures

The stored procedure is actually a function

CALL productpricing();

4. Delete the stored procedure

    drop procedure productpricing;
    drop procedure if EXISTS productpricing;

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;

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);

Query

SELECT @priceaverage;
SELECT @priceaverage,@pricehign,@pricelow;

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;

Calling

call ordertotal(20005,@total);

Query

select @total;

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、返回合计(带或不带税的)

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

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

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

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;

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

show procedure status;

There are many tables, use like to filter

show procedure status like 'ordertotal';

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
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software