MySQL - stored procedures and stored functions

MySQL 5.0版本supports 存储过程and from the beginning 存储函数. Stored procedures and functions can encapsulate complex SQL logic together, and applications do not need to pay attention to the complex SQL logic inside stored procedures and functions, but only need to simply call stored procedures and functions.

1. Overview of stored procedures

1.1 Understanding

含义: The English of the stored procedure is Stored Procedure. Its idea is very simple, it is the encapsulation of a set of pre-compiled SQL statements.
执行过程: The stored procedure is pre-stored on the MySQL server. When it needs to be executed, the client only needs to send a command to the server to call the stored procedure, and the server can execute all the pre-stored series of SQL statements.

好处:
1. Simplify operation, improve the reusability of sql statements, and reduce the pressure on development programmers
2. Reduce errors in the operation process and improve efficiency
3. Reduce network transmission volume (the client does not need to send all SQL statements through the network 4. Reduce the risk of SQL statements being exposed to the Internet
, and also improve the security of data query

和视图、函数的对比:
It has the same advantages as the view, it is clear, safe, and can reduce the amount of network transmission. However, it is different from views. Views 虚拟表usually do not operate directly on the underlying data tables, while stored procedures are programmatic SQL. 直接操作底层数据表Compared with set-oriented operations, they can achieve some more complex data processing.

Once a stored procedure is created, using it is as easy as using a function, we just call the stored procedure name. Compared to functions, stored procedures are 没有返回值的.

1.2 Classification

The parameter type of the stored procedure can be IN、OUT和INOUT. According to this classification is as follows:

  • no parameters (no parameters no return)
  • Only with IN type (with parameters but no return)
  • Only with OUT type (no parameter and return)
  • With both IN and OUT (with parameters and returns)
  • With INOUT (with parameters and returns)

注意: Multiple IN, OUT, and INOUT can be included in one stored procedure.

2. Create a stored procedure

2.1 Syntax Analysis

grammar:

CREATE PROCEDURE 存储过程名(IN|OUT|INOUT 参数名 参数类型,...)
[characteristics ...]
BEGIN
	存储过程体
	
END

Similar to the method in Java:

修饰符 返回类型 方法名(参数类型 参数名,...){
	方法体;
}

说明:
1. The meaning of the symbol in front of the parameter

  • IN: The current parameter is an input parameter, that is, an input parameter;
    the stored procedure just reads the value of this parameter. If no parameter type is defined, 默认就是 IN, means an input parameter.
  • OUT: The current parameter is an output parameter, that is, an output parameter;
    after the execution is completed, the client or application that calls this stored procedure can read the value returned by this parameter.
  • INOUT: The current parameter can be either an input parameter or an output parameter.

2. The formal parameter type can be any type in the MySQL database.

3. characteristicsIndicates the constraints on the stored procedure specified when creating the stored procedure, and its value information is as follows:

LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'

4. There can be multiple SQL statements in the stored procedure body. If there is only one SQL statement, BEGIN and END can be omitted.

1. BEGINENDBEGINEND 中间包含了多个语句,每个语句都以(;)号为结束符。
2. DECLAREDECLARE 用来声明变量,使用的位置在于 BEGINEND 语句中间,而且需要在其他语句使用之前进
行变量的声明。
3. SET:赋值语句,用于对变量进行赋值。
4. SELECTINTO:把从数据表中查询的结果存放到变量中,也就是为变量赋值。

5. Need to set a new end tag

DELIMITER 新的结束标记

Because the MySQL default statement end symbol is a semicolon ';'. In order to avoid conflict with the terminator of the SQL statement in the stored procedure, you need to use
DELIMITER to change the terminator of the stored procedure.

示例:

DELIMITER $

CREATE PROCEDURE 存储过程名(IN|OUT|INOUT 参数名 参数类型,...)
[characteristics ...]
BEGIN
	sql语句1;
	sql语句2;
END $

2.2 Code example

Example 1: Create a stored procedure select_all_data() to view all data in the emps table

DELIMITER $

CREATE PROCEDURE select_all_data()
BEGIN
	SELECT * FROM emps;
END $

DELIMITER ;

Example 2: Create a stored procedure show_max_salary() to view the maximum salary value of the "emps" table.

DELIMITER //

CREATE PROCEDURE show_max_salary()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT '查看最高薪资'

BEGIN
	SELECT MAX(salary) FROM emps;
END //

DELIMITER ;

Example 3: Create a stored procedure show_someone_salary2() to view the salary of an employee in the "emps" table, and use the IN parameter empname to
input the employee's name, and use the OUT parameter empsalary to output the employee's salary.

CREATE PROCEDURE show_someone_salary2(IN empname VARCHAR(20),OUT empsalary DOUBLE)
BEGIN
	SELECT salary INTO empsalary FROM emps WHERE ename = empname;
END //
DELIMITER ;

Example 4: Create a stored procedure show_mgr_name() to query the name of an employee's leader, and use the INOUT parameter "empname" to input the employee's
name and output the leader's name.

DELIMITER //

CREATE PROCEDURE show_mgr_name(INOUT empname VARCHAR(20))
BEGIN
	SELECT ename INTO empname FROM emps
	WHERE eid = (SELECT MID FROM emps WHERE ename=empname);
END //

DELIMITER ;

3. Call the stored procedure

3.1 Call format

There are several ways to call a stored procedure. The stored procedure must be called with the CALL statement, and the stored procedure is related to the database. If you want to execute the stored procedure in another database, you need to specify the database name, such as CALL dbname.procname.

CALL 存储过程名(实参列表)

格式:
1. Call the parameters of in mode:

CALL sp1('值');

2. Call the parameters of the out mode:

SET @name;
CALL sp1(@name);
SELECT @name;

3. Call the parameters of inout mode:

SET @name=;
CALL sp1(@name);
SELECT @name;

3.2 Code example

Create a stored procedure, realize the accumulation operation, and calculate what 1+2+…+n is equal to. The specific code is as follows:

DELIMITER //

CREATE PROCEDURE `add_num`(IN n INT)
BEGIN
	DECLARE i INT;
	DECLARE sum INT;
	
	SET i = 1;
	SET sum = 0;
	WHILE i <= n DO
		SET sum = sum + i;
		SET i = i +1;
	END WHILE;
	SELECT sum;
END //
DELIMITER ;

Just use directly CALL add_num(50);. Here I pass in a parameter of 50, which is the cumulative sum of statistics 1+2+…+50.

3.3 How to debug

In MySQL, stored procedures do not have a dedicated integrated development environment like ordinary programming languages ​​(such as VC++, Java, etc.). Therefore, you can query the intermediate results of program execution through the SELECT statement to debug the correctness of an SQL statement. After the debugging is successful, move the SELECT statement to the next SQL statement, and then debug the next SQL statement. In this way 逐步推进, you can complete the debugging of all operations in the stored procedure. Of course, you can also copy the SQL statement in the stored procedure and debug it segment by segment.

4. Use of stored functions

We have learned a lot of functions before, and using these functions can perform various processing operations on data, which greatly improves the user's management efficiency of the database. MySQL supports user-defined functions. After they are defined, they can be called in the same way as calling MySQL's predefined system functions.

4.1 Syntax Analysis

学过的函数:LENGTH、SUBSTR、CONCAT等
语法格式:

CREATE FUNCTION 函数名(参数名 参数类型,...)
RETURNS 返回值类型
[characteristics ...]
BEGIN
	函数体 #函数体中肯定有 RETURN 语句
END

说明:
1. Parameter list: It is only true if the specified parameter is IN, OUT PROCEDUREor INOUT 合法的. 2. The RETURNS type statement indicates the type of data returned by the function;FUNCTION中总是默认为IN参数

  • The RETURNS clause can only FUNCTIONbe specified for a function, which is mandatory. It is used to specify the return type of the function, and the function
    body must contain a RETURN value statement.

3. characteristic Constraints on the function specified when creating the function. The value is the same as when creating the stored procedure, and will not be repeated here.
4. The function body can also use BEGIN...END to indicate the beginning and end of the SQL code. If the function body has only one statement, BEGIN...END can also be omitted.

4.2 Call stored function

In MySQL, the usage of stored functions is the same as that of MySQL internal functions. In other words, user-defined stored functions are of the same nature as MySQL internal functions. The difference is that stored functions are 用户自己定义MySQL's, while internal functions are MySQL's 开发者定义.

SELECT 函数名(实参列表)

4.3 Code Example

举例1:
Create a stored function with the name email_by_id(). The parameter is passed to emp_id. This function queries the email of emp_id and returns it. The data type is a string.

DELIMITER //

CREATE FUNCTION email_by_id(emp_id INT)
RETURNS VARCHAR(25)
DETERMINISTIC
CONTAINS SQL
BEGIN
	RETURN (SELECT email FROM employees WHERE employee_id = emp_id);
END //

DELIMITER ;
SET @emp_id = 102;
SELECT email_by_id(102);

注意:
If an error is reported in the creation of the storage function “ you might want to use the less safelog_bin_trust_function_creators variable ”, there are two ways to deal with it:

  • Method 1: Add the necessary function features "[NOT] DETERMINISTIC" and "{CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA}"
  • SET GLOBAL log_bin_trust_function_creators = 1;

4.4 Comparing stored functions and stored procedures

keywords call syntax return value Application Scenario
stored procedure PROCEDURE CALL stored procedure() understood as having 0 or more Generally used for updating
stored function FUNCTION SELECT function() can only be one Generally used when the query result is a value and returned

In addition, 存储函数可以放在查询语句中使用,存储过程不行. On the contrary, the functions of stored procedures are more powerful, including the ability to
perform operations on tables (such as creating tables, deleting tables, etc.) and transaction operations, which are not available in stored functions.

5. View, modify and delete stored procedures and functions

5.1 view

After creation, how do we know whether the stored procedures and stored functions we created are successful?
MySQL stores the status information of stored procedures and functions. Users can use the SHOW STATUS statement or SHOW CREATE statement to view it, or directly query it from the information_schema database of the system. Here are 3 methods.
1. 使用SHOW CREATE语句查看存储过程和函数的创建信息

SHOW CREATE {
   
   PROCEDURE | FUNCTION} 存储过程名或函数名

SHOW CREATE FUNCTION test_db.CountProc \G

2. 使用SHOW STATUS语句查看存储过程和函数的状态信息

SHOW {
   
   PROCEDURE | FUNCTION} STATUS [LIKE 'pattern']

3. 从information_schema.Routines表中查看存储过程和函数的信息
Information about stored procedures and functions in MySQL is stored in the Routines table under the information_schema database. Information about stored procedures and functions can be queried by querying the records of this table. Its basic syntax is as follows:

SELECT * FROM information_schema.Routines
WHERE ROUTINE_NAME='存储过程或函数的名' [AND ROUTINE_TYPE = {
   
   'PROCEDURE|FUNCTION'}];

Note: If the stored procedure and function have the same name in the MySQL database, it is best to specify the ROUTINE_TYPE query condition to
indicate whether the query is a stored procedure or a function.

5.2 Modification

Modifying a stored procedure or function does not affect the function of the stored procedure or function, but only modifies the relevant characteristics. Use the ALTER statement to achieve.

ALTER {
   
   PROCEDURE | FUNCTION} 存储过程或函数的名 [characteristic ...]

Among them, characteristic specifies the characteristics of the stored procedure or function, and its value information is slightly different from the value information when creating the stored procedure or function.

{ CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'
  • CONTAINS SQL, indicating that the subroutine contains SQL statements, but does not contain statements for reading or writing data.
  • NO SQL, indicating that the subroutine does not contain SQL statements.
  • READS SQL DATA , indicating that the subroutine contains the statement of reading data.
  • MODIFIES SQL DATA, indicating that the subroutine contains a statement for writing data.
  • SQL SECURITY { DEFINER | INVOKER }, indicating who has permission to execute.
    • DEFINER, indicating that only the definer can execute it.
    • INVOKER, indicating that the caller can execute.
  • COMMENT 'string' , indicating annotation information.
ALTER PROCEDURE CountProc
MODIFIES SQL DATA
SQL SECURITY INVOKER ;
ALTER FUNCTION CountProc
READS SQL DATA
COMMENT 'FIND NAME' ;

5.3 Delete

To delete stored procedures and functions, you can use the DROP statement, whose grammatical structure is as follows:

DROP {
   
   PROCEDURE | FUNCTION} [IF EXISTS] 存储过程或函数的名

IF EXISTS: It prevents errors from occurring if the program or function is not stored, generating a warning that can be viewed with SHOW WARNINGS.

6. Controversy over the use of stored procedures

Although stored procedures have many advantages, for the use of stored procedures, 一直都存在着很多争议for example, some companies require the use of stored procedures for large-scale projects, while some companies explicitly prohibit the use of stored procedures in their manuals. Why do these companies have such different requirements for the use of stored procedures? Woolen cloth?

6.1 Advantages

  • 1、存储过程可以一次编译多次使用. The stored procedure is only compiled when it is created, and it does not need to be recompiled for subsequent use, which improves the execution efficiency of SQL.
  • 2、可以减少开发工作量. Dividing the code 封装into modules is actually one of the core ideas of programming. In this way, complex problems can be disassembled into different modules, and then the modules can be separated. 重复使用While reducing the development workload, it can also ensure the clear structure of the code.
  • 3、存储过程的安全性强. When we set the stored procedure 设置对用户的使用权限, it can be as strong as the view.
  • 4、可以减少网络传输量. Because the code is encapsulated into the stored procedure, each use only needs to call the stored procedure, which reduces the amount of network transmission.
  • 5、良好的封装性. When performing relatively complex database operations, it was originally necessary to use one SQL statement one by one, and it may take multiple connections to the database to complete the operation. Now it has become a stored procedure and only needs to be executed 连接一次即可.

6.2 Disadvantages

Based on the above advantages, many large companies require large projects to use stored procedures, such as Microsoft, IBM and other companies. However, Ali in China does not recommend developers to use stored procedures. Why is this?

Ali development specification

[Mandatory] The use of stored procedures is prohibited. Stored procedures are difficult to debug and expand, and they are not portable.

Although stored procedures have benefits such as the above, but the disadvantages are also obvious.

  • 1、可移植性差. Stored procedures cannot be transplanted across databases. For example, stored procedures written in MySQL, Oracle, and SQL Server need to be rewritten when they are replaced with other databases.
  • 2、调试困难. Only a few DBMSs support debugging of stored procedures. For complex stored procedures, development and maintenance are not easy. Although there are some third-party tools that can debug stored procedures, they are charged.
  • 3、存储过程的版本管理很困难. For example, if the index of the data table changes, it may cause the stored procedure to fail. We often need to perform version management when developing software, but the stored procedure itself has no version control, and it is troublesome to iteratively update the version.
  • 4、它不适合高并发的场景. High concurrency scenarios need to reduce the pressure on the database. Sometimes the database will adopt the method of sub-database and sub-table, and has high requirements for scalability. In this case, the stored procedure will become difficult to maintain. Obviously, it is not 增加数据库的压力 applicable .

Stored procedures are both convenient and limiting. Although different companies have different attitudes towards stored procedures, for us developers,
mastering stored procedures is one of the necessary skills no matter what.

Guess you like

Origin blog.csdn.net/weixin_56650035/article/details/131340358