MySQL 5.0 has supported stored procedures since its release.
A stored procedure is a database object that stores complex programs in the database for invocation by external programs.
A stored procedure is a set of SQL statements designed to accomplish a specific function. It is compiled, created, and saved in the database. Users can call and execute it by specifying the stored procedure's name and providing parameters (when needed).
The idea behind stored procedures is simple: code encapsulation and reuse at the SQL language level of the database.
Advantages
- Stored procedures can encapsulate and hide complex business logic.
- Stored procedures can return values and accept parameters.
- Stored procedures cannot be run using the SELECT command because they are subroutines, unlike views, tables, or user-defined functions.
- Stored procedures can be used for data validation, enforcing business logic, and so on.
Disadvantages
- Stored procedures are often customized to specific databases because the supported programming languages differ. When switching to another vendor's database system, existing stored procedures need to be rewritten.
- The performance tuning and writing of stored procedures are limited by various database systems.
I. Creation and Invocation of Stored Procedures
- A stored procedure is a named block of code used to accomplish a specific function.
- Created stored procedures are stored in the database's data dictionary.
Creating a Stored Procedure
Key syntax in MySQL stored procedures
Declare the statement delimiter; it can be customized:
DELIMITER $$ 或 DELIMITER //
Declare the stored procedure:
CREATE PROCEDURE demo_in_parameter(IN p_in int)
Stored procedure start and end symbols:
BEGIN .... END
Variable assignment:
SET @p_in=1
Variable definition:
DECLARE l_int int unsigned default 4000000;
Create MySQL stored procedures and stored functions:
create procedure 存储过程名(参数)
Stored procedure body:
create function 存储函数名(参数)
Example
Create a database and back up a data table for the example operation:
The following is an example of a stored procedure that deletes all matches in which a given player participated:
Analysis:By default, a stored procedure is associated with the default database. If you want to create the stored procedure under a specific database, prefix the procedure name with the database name. When defining the procedure, useDELIMITER $$command to change the statement delimiter from a semicolon;temporarily to two$$, so that semicolons used in the procedure body are passed directly to the server and are not interpreted by the client (such as mysql).
Calling the stored procedure:
call sp_name[(传参)];
Analysis:In the stored procedure, a variable p_playerno requiring a parameter is set. When calling the stored procedure, 57 is assigned to p_playerno via the parameter, and then the SQL operations in the stored procedure are executed.
Stored procedure body
- The stored procedure body contains the statements that must be executed when the procedure is called, such as DML and DDL statements, IF-THEN-ELSE and WHILE-DO statements, DECLARE statements for declaring variables, etc.
- Procedure body format: starts with BEGIN and ends with END (can be nested)
BEGIN BEGIN BEGIN statements; END END END
Note:Each nested block and each statement within it must end with a semicolon. The BEGIN-END block that marks the end of the procedure body (also called a compound statement) does not require a semicolon.
Labeling statement blocks:
[begin_label:] BEGIN [statement_list] END [end_label]
For example:
Labels have two purposes:
- 1. Enhance code readability
- 2. Certain statements (e.g., LEAVE and ITERATE statements) require labels
II. Parameters of Stored Procedures
MySQL stored procedure parameters are used in the definition of stored procedures. There are three parameter types: IN, OUT, and INOUT, in the form of:
CREATEPROCEDURE 存储过程名([[IN |OUT |INOUT ] 参数名 数据类形...])
- IN input parameter: indicates that the caller passes a value into the procedure (the input value can be a literal or a variable)
- OUT output parameter: indicates that the procedure passes a value out to the caller (can return multiple values) (the output value can only be a variable)
- INOUT input/output parameter: indicates that the caller passes a value into the procedure and that the procedure passes a value out to the caller (the value can only be a variable)
1. IN Input Parameter
From the above, it can be seen that p_in is modified in the stored procedure, but it does not affect@p_inthe value of the latter, because the former is a local variable and the latter is a global variable.
2. OUT Output Parameter
3. INOUT Input/Output Parameter
Note:
1. If the procedure has no parameters, you must still write parentheses after the procedure name. For example:
CREATE PROCEDURE sp_name ([proc_parameter[,...]]) ……
2. Ensure that parameter names are not equal to column names; otherwise, in the procedure body, the parameter name will be treated as a column name.
Suggestions:
- Use IN parameters for input values.
- Use OUT parameters for return values.
- Use INOUT parameters as little as possible.
III. Variables
1. Variable Definition
Local variable declarations must be placed at the beginning of the stored procedure body:
DECLAREvariable_name [,variable_name...] datatype [DEFAULT value];
Here, datatype is a MySQL data type, such as INT, FLOAT, DATE, VARCHAR(length)
For example:
2. Variable Assignment
SET 变量名 = 表达式值 [,variable_name = expression ...]
3. User Variables
Using user variables in the MySQL client:
Using user variables in stored procedures
Passing user variables with global scope between stored procedures
Note:
- 1. User variable names generally begin with @
- 2. Overusing user variables can make the program difficult to understand and manage
IV. Comments
MySQL stored procedures can use two styles of comments
Two hyphens--: This style is generally used for single-line comments.
C style: Generally used for multi-line comments.
For example:
Calling MySQL Stored Procedures
Use CALL followed by your procedure name and parentheses. Inside the parentheses, add parameters as needed. Parameters include input parameters, output parameters, and input/output parameters. For specific calling methods, refer to the examples above.
Querying MySQL Stored Procedures
If we want to know which tables exist under a database, we generally useshowtables;to view them. Then, if we want to view the stored procedures under a database, can we also use this method? The answer is: we can view the stored procedures under a database, but in a different way.
We can use the following statement to query:
selectname from mysql.proc where db='数据库名'; 或者 selectroutine_name from information_schema.routines where routine_schema='数据库名'; 或者 showprocedure status where db='数据库名';
If we want to know the details of a specific stored procedure, what should we do? Can we also use DESCRIBE table_name to view it just like we do with tables?
The answer is:We can view the details of the stored procedure, but we need to use another method:
SHOW CREATE PROCEDURE 数据库.存储过程名;
to view the details of the current stored procedure.
Modifying MySQL Stored Procedures
ALTER PROCEDURE
Altering a previously specified stored procedure created with CREATE PROCEDURE does not affect related stored procedures or stored functions.
Dropping MySQL Stored Procedures
Dropping a stored procedure is relatively simple, just like dropping a table:
DROPPROCEDURE
Drop one or more stored procedures from the MySQL table.
Control Statements in MySQL Stored Procedures
(1). Variable Scope
Inner variables have higher priority within their scope. When execution reaches END, inner variables disappear. At that point, they are already outside their scope and the variables are no longer visible, because this declared variable can no longer be found outside the stored procedure. However, you can save its value through an OUT parameter or by assigning its value to a session variable.
(2). Conditional statements
1. if-then-else statements
2. case statement:
(3). Loop statements
1. while ···· end while
while 条件 do
--循环体
endwhile
2. repeat···· end repeat
It checks the result after performing the operation, whereas while checks before executing.
repeat
--循环体
until 循环条件
end repeat;
3. loop ·····endloop
The loop loop does not require an initial condition, similar to the while loop, and like the repeat loop, it does not require an ending condition. The leave statement is used to exit the loop.
4. LABELS:
Labels can be placed before begin, repeat, while, or loop statements. Statement labels can only be used before legal statements. They can break out of a loop, causing the running instructions to reach the final step of the compound statement.
(4). ITERATE iteration
ITERATE restarts a compound statement by referencing its label:
Reference articles:
https://www.cnblogs.com/geaozhang/p/6797357.html
http://blog.sina.com.cn/s/blog_86fe5b440100wdyt.html