Home > Database > Mysql Tutorial > body text

mysql c stored procedure

PHPz
Release: 2023-05-14 13:24:07
Original
1080 people have browsed it

MySQL is a very commonly used relational database management system, which can be used to store, process and manage large amounts of data. Stored procedures are a very useful function provided by MySQL. They can encapsulate a series of SQL statements into a reusable code block, thereby improving the execution efficiency of SQL statements, reducing code complexity, improving security, etc. Therefore, mastering the use of MySQL stored procedures is of great significance to improving the efficiency of database development and management.

1. Introduction to stored procedures

Stored procedures are a collection of precompiled SQL statements defined in MySQL. They are compiled in the database server. When querying, you only need to call the stored procedures. . Compared with executing SQL statements alone, stored procedures can significantly reduce network overhead and improve the efficiency of data query and processing.

In addition, stored procedures have the following important features:

  1. Security: Users’ access rights to the database and data access methods can be controlled through stored procedures.
  2. Logic: Stored procedures can complete complex data operations, such as calculations, loops, judgments, etc.
  3. Maintainability: Stored procedures can increase code reuse and reduce the amount of code, thereby facilitating database maintenance and updates.

2. Syntax format of stored procedures

To define a stored procedure in MySQL, you need to use the CREATE PROCEDURE statement. The following is the basic syntax format of the CREATE PROCEDURE statement:

CREATE PROCEDURE 存储过程名称(参数列表)
BEGIN
    -- sql语句
END;
Copy after login

Among them, the stored procedure name is required, and the parameter list can be omitted as needed. Between BEGIN and END, you can write a series of SQL statements to perform data query, writing, modification and other related operations.

The following is a simple example of a stored procedure. The stored procedure has only one parameter and simply returns it after modifying it:

CREATE PROCEDURE test_proc(IN num INT)
BEGIN
    SET num = num + 1;
    SELECT num;
END;
Copy after login

When executing the stored procedure, it can be called through the CALL statement :

CALL test_proc(10);
Copy after login

The execution result is 11.

3. Parameters in stored procedures

In stored procedures, you can use three types of parameters: IN, OUT and INOUT.

  1. IN parameter: represents the parameter value passed in the stored procedure, which can be read and modified in the stored procedure.
  2. OUT parameter: represents the parameter value output in the stored procedure, which can return one or more results.
  3. INOUT parameter: Indicates the input and output parameter values ​​in the stored procedure, that is, it can be used as either an input parameter or an output parameter.

The following is an example of a stored procedure with parameters:

CREATE PROCEDURE get_user_by_id(IN userid INT, OUT username VARCHAR(50))
BEGIN
    SELECT username FROM user WHERE id=userid;
    SET username = CONCAT('Welcome, ', username);
END;
Copy after login

When calling this stored procedure, you need to pass in the userid parameter and define a variable to receive the username output parameter:

DECLARE uname VARCHAR(50);
CALL get_user_by_id(1, @uname);
SELECT @uname;
Copy after login

4. Flow control and looping in stored procedures

In addition to directly executing SQL statements, stored procedures can also use flow control statements and looping statements to complete specific logical operations. MySQL supports the following flow control statements:

  1. IF, ELSEIF and ELSE: used to implement conditional branches.
  2. CASE, WHEN and ELSE: used to implement multiple conditional branches.
  3. LOOP and END LOOP: used to implement simple loops.
  4. WHILE DO and END WHILE: used to implement complex loops.

The following is an example of a WHILE DO loop. This stored procedure adds 1 year to the age in the user table:

CREATE PROCEDURE update_user_age()
BEGIN
    DECLARE i INT DEFAULT 0;
    DECLARE n INT;
    SELECT COUNT(*) FROM user INTO n;
    WHILE i<=n DO
        UPDATE user SET age=age+1 WHERE id=i;
        SET i=i+1;
    END WHILE;
END;
Copy after login

When executing this stored procedure, you only need to call:

CALL update_user_age();
Copy after login

5. Exception handling in stored procedures

When an error occurs in a stored procedure, exception handling can be used to avoid program crashes. In MySQL, exception handling is implemented using the DECLARE ... HANDLER syntax.

The following is an example of exception handling. When deleting a user table record, the stored procedure will throw an exception if the record has been referenced by other tables.

CREATE PROCEDURE delete_user(IN userid INT)
BEGIN
    DECLARE exit_test CONDITION FOR SQLSTATE '23000';
    START TRANSACTION;
    DELETE FROM user WHERE id=userid;
    IF ROW_COUNT() = 0 THEN
        SIGNAL exit_test;
    END IF;
    COMMIT;
END;
Copy after login

When executing the stored procedure, if an exception occurs, you can write the following program code to handle it:

DECLARE EXIT HANDLER FOR SQLSTATE '23000'
    -- 处理异常
END;    
Copy after login

6. Optimization of the stored procedure

Although the stored procedure It can improve the efficiency of SQL queries, but if the stored procedure design is unreasonable, it may also lead to a decrease in query efficiency. The following are some optimization suggestions for stored procedures:

  1. Avoid using too many temporary variables and loop statements, which will greatly reduce the execution efficiency of stored procedures.
  2. When using flow control statements, RETURN should be used instead of SELECT.
  3. Using Prepared Statement statements in stored procedures to query and update data can improve query efficiency.
  4. Consider using views or join queries instead of stored procedures.

In short, stored procedures are a very important function in MySQL. It can improve the execution efficiency of SQL statements, reduce code complexity, improve security, etc. When using stored procedures, you need to pay attention to parameters, process control, exception handling, etc. You also need to consider how to improve database query and update efficiency by optimizing stored procedures.

The above is the detailed content of mysql c stored procedure. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template