11_MySQL stored procedure

1. Introduction to MySQL stored procedures

Stored procedures are an important function of database storage, but MySQL does not support stored procedures before 5.0, which makes MySQL greatly reduced in application. Fortunately, MySQL 5.0 has finally begun to support stored procedures, which can greatly improve the processing speed of the database, but also improve the flexibility of database programming.

A stored procedure is a set of SQL statements to complete a specific function . The purpose of using a stored procedure is to write common or complex work in advance with SQL statements and store it with a specified name. This procedure is compiled and optimized and stored in the database server, so it is called a stored procedure. When you need the database to provide the same service as the defined stored procedure in the future, you only need to call the "CALL stored procedure name" to automatically complete it.

SQL statements commonly used to operate databases need to be compiled and then executed when they are executed. The stored procedure uses another way to execute SQL statements.

A stored procedure is a programmable function, which is created and saved in the database, generally composed of SQL statements and some special control structures. When you want to perform the same specific function on different applications or platforms, stored procedures are particularly suitable.

Stored procedures usually have the following advantages

(1) After the encapsulated stored procedure is created, it can be called multiple times in the program without having to rewrite the SQL statement of the stored procedure, and database professionals can modify the stored procedure at any time without affecting the call to it Application source code.

(2) The function and flexibility of SQL statements can be enhanced. Stored procedures can be written with flow control statements, which have strong flexibility and can complete complex judgments and more complex calculations.

(3) It can reduce network traffic. Because the stored procedure runs on the server side and the execution speed is fast, when the stored procedure is called on the client computer, only the call statement is transmitted on the network, which can reduce the network load.

(4) After the high-performance stored procedure is executed once, the generated binary code resides in the buffer. In subsequent calls, only the binary code needs to be executed from the buffer, thereby improving the efficiency and performance of the system.

(5) Improve database security and data integrity. Use stored procedures to complete all database operations, and you can programmatically control database information access permissions.

Two, create a stored procedure (CREATE PROCEDURE)

MySQL stored procedure is a collection of some SQL statements. For example, sometimes we may need a large series of SQL statements, or we need to set the value of some variables in the process of writing SQL statements. At this time, it is completely necessary for us to write a storage process.

Note: When creating a stored procedure, you must have CREATE ROUTINE permission.
Syntax format:

CREATE PROCEDURE <过程名> ( [过程参数[,…] ] ) <过程体> [过程参数[,…] ] 格式 [ IN | OUT | INOUT ] <参数名> <类型>

The syntax description is as follows:

(1) Procedure name The name of the stored procedure, which is created in the current database by default. If you need to create a stored procedure in a specific database, you must prefix the name with the name of the database, that is, db_name.sp_name. It should be noted that the name should be avoided as far as possible to choose the same name as the MySQL built-in function, otherwise an error will occur.

(2) Process parameter The parameter list of the stored procedure. Among them, <parameter name> is the name of the parameter, and <type> is the type of the parameter (it can be any valid MySQL data type). When there are multiple parameters, the parameter list is separated by commas. The stored procedure can have no parameters (at this time, a pair of parentheses still need to be added after the name of the stored procedure), or it can have one or more parameters.
MySQL stored procedures support three types of parameters, namely input parameters, output parameters, and input/output parameters, which are identified by the three keywords IN, OUT, and INOUT, respectively. Among them, input parameters can be passed to a stored procedure, and output parameters are used when the stored procedure needs to return an operation result, and input/output parameters can serve as input parameters or output parameters. It should be noted that the name of the parameter should not be the same as the column name of the data table, otherwise, although no error message will be returned, the SQL statement of the stored procedure will treat the parameter name as the column name, causing unpredictable results.

(3) Procedure body The main part of the stored procedure, also called the stored procedure body, contains the SQL statements that must be executed when the procedure is called. This section starts with the keyword BEGIN and ends with the keyword END. If there is only one SQL statement in the stored procedure body, you can omit the BEGINEND flag.
In the creation of stored procedures, a very important MySQL command is often used, that is, the DELIMITER command. Especially for users who operate the MySQL database through the command line, it is necessary to learn to use this command.
In MySQL, the server processes SQL statements by default with a semicolon as the end of the statement. However, when creating a stored procedure, the body of the stored procedure may contain multiple SQL statements. If these SQL statements still use a semicolon as the statement terminator, the MySQL server will end with the first SQL statement encountered during processing. The semicolon as the end character of the entire program, and no longer deal with the SQL statement later in the stored procedure body, this obviously does not work. To solve this problem, you can usually use the DELIMITER command to modify the end command to other characters.

语法:DELIMITER $$

The syntax description is as follows: $$ is a user-defined terminator, usually this symbol can be some special symbols, such as two "?" or two "¥". When using the DELIMITER command, you should avoid using the backslash "\" character, because it is an escape character for MySQL.

mysql> delimiter ##

After successfully executing this SQL statement, the end sign of any command, statement or program is replaced by two question marks "##".

If you want to change back to the default semicolon ";" as the end sign, enter the following statement in the MySQL command line client

mysql> delimiter ;

Example 1
//The stored procedure creates the tt1 table

mysql> delimiter ##
mysql> create procedure t1()
    ->      begin
    ->      create table tt1 (id int,name varchar(30));
    ->      end ##
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call t1();
Query OK, 0 rows affected (0.01 sec)

//The stored procedure inserts data into the tt1 table

mysql> delimiter ##
mysql> create procedure t2()
    -> begin
    -> insert into tt1 values(1,'zhangsan');
    -> insert into tt1 values(2,'lisi');
    -> insert into tt1 values(3,'wangwu');
    -> insert into tt1 values(4,'maliu');
    -> insert into tt1 values(5,'liuqi');
    -> end##
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call t2();
Query OK, 1 row affected (0.00 sec)

//View all data in the tt1 table through the stored procedure

mysql> create procedure t3()
    -> begin
    -> select * from tt1;
    -> end ##

mysql> delimiter ;
mysql> call t3();
+------+----------+
| id   | name     |
+------+----------+
|    1 | zhangsan |
|    2 | lisi     |
|    3 | wangwu   |
|    4 | maliu    |
|    5 | liuqi    |
+------+----------+
5 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

//Use the stored procedure with parameters to view the specified id data

mysql> delimiter ##
mysql> create procedure t4(in a int)
    -> begin
    -> select * from tt1 where id=a;
    -> end##
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call t4(2); #查看id为2数据
+------+------+
| id   | name |
+------+------+
|    2 | lisi |
+------+------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> call t4(4); #查看id为4数据
+------+-------+
| id   | name  |
+------+-------+
|    4 | maliu |
+------+-------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Example 2
The difference between the parameters [in, out, inout] of the stored procedure
(1) The result of the out
parameter out in the stored procedure will be brought locally. For example, the variables defined in the stored procedure will also be brought locally.

mysql> create procedure t6(out a int) 
    -> begin 
    -> select a; 
    -> set a=100;
    -> select a;
    -> end ##
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call t6(@t1);
+------+
| a    | #不管变量之前是否有值都会显示null
+------+
| NULL |
+------+
1 row in set (0.00 sec)

+------+
| a    |
+------+
|  100 |
+------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> select @t1; #存储过程中数据会带到本地来
+------+
| @t1  |
+------+
|  100 |
+------+
1 row in set (0.00 sec)

(2)
The difference between in in and out is that the data in in in the storage process will not be output to the local

mysql> delimiter ##
mysql> create procedure t5(in a int)
    -> begin
    -> select a;
    -> set a=100;
    -> select a;
    -> end ##
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> set @t1=33; #设置变量t1值为33
Query OK, 0 rows affected (0.00 sec)

mysql> select @t1;
+------+
| @t1  |
+------+
|   33 | 
+------+
1 row in set (0.00 sec)

mysql> call t5(@t1);
+------+
| a    |
+------+
|   33 | #显示修改前变量的值
+------+
1 row in set (0.00 sec)

+------+
| a    |
+------+
|  100 |
+------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> select @t1; #变量t1值还是33没有改变
+------+
| @t1  |
+------+
|   33 |
+------+

(3) inout
Inout is a combination of in and out. It has the function of displaying the variable value before modification of in and the function of inputting out to local.

mysql> select @t1; #t1变量为33
+------+
| @t1  |
+------+
|   33 |
+------+
1 row in set (0.00 sec)

mysql> delimiter ##
mysql> create procedure t7(inout a int)
    -> begin
    -> select a;
    -> set a=100;
    -> select a;
    -> end ##
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call t7(@t1);
+------+
| a    |
+------+
|   33 | #显示变量修改前的值
+------+
1 row in set (0.00 sec)

+------+
| a    |
+------+
|  100 |
+------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> select @t1;  #和out一样输入变量到本地了
+------+
| @t1  |
+------+
|  100 |
+------+
1 row in set (0.00 sec)

Example 3
//Create student and insert data

mysql> delimiter ##
mysql> create procedure t8()
    -> begin
    -> create table student(id int,name varchar(20),sex varchar(33),scores float);
    -> insert into student values (1,'张三',"男",90.5);
    -> insert into student values (2,'李四',"男",85.5);
    -> insert into student values (3,'王五',"女",78.5);
    -> insert into student values (4,'马六',"女",66.5);
    -> insert into student values (5,'刘七',"男",50.5);
    -> insert into student values (6,'李九',"女",30.5);
    -> select * from student;
    -> end ##
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call t8();
+------+--------+------+--------+
| id   | name   | sex  | scores |
+------+--------+------+--------+
|    1 | 张三   ||   90.5 |
|    2 | 李四   ||   85.5 |
|    3 | 王五   ||   78.5 |
|    4 | 马六   ||   66.5 |
|    5 | 刘七   ||   50.5 |
|    6 | 李九   ||   30.5 |
+------+--------+------+--------+
6 rows in set (0.01 sec)

Query OK, 0 rows affected (0.01 sec)

//Use the if statement to view sex specified men and women

mysql> delimiter ##
mysql> create procedure t9(in a char)
    -> begin
    -> if a="男" then
    -> select * from student where sex="男";
    -> else
    -> select * from student where sex="女";
    -> end if;
    -> end ##
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call t9('男');
+------+--------+------+--------+
| id   | name   | sex  | scores |
+------+--------+------+--------+
|    1 | 张三   ||   90.5 |
|    2 | 李四   ||   85.5 |
|    5 | 刘七   ||   50.5 |
+------+--------+------+--------+
3 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> call t9('女');
+------+--------+------+--------+
| id   | name   | sex  | scores |
+------+--------+------+--------+
|    3 | 王五   ||   78.5 |
|    4 | 马六   ||   66.5 |
|    6 | 李九   ||   30.5 |
+------+--------+------+--------+
3 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Example 4

Use case statement

mysql> create procedure t10(in t int)
    -> begin
    -> case t
    -> when 1 then
    -> select * from student where scores>90;
    -> when 2 then
    -> select * from student where scores>80 and scores<=90;
    -> when 3 then
    -> select * from student where scores>60 and scores<=80;
    -> when 4 then 
    -> select * from student where scores<60;
    -> else
    -> select * from student;
    -> end case;
    -> end ##
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;

//The effect after completion

1= scores>90+
2= scores>80~90
3= scores>60~80
4=scores <60
*= scores> all

mysql> call t10(1);
+------+--------+------+--------+
| id   | name   | sex  | scores |
+------+--------+------+--------+
|    1 | 张三   ||   90.5 |
+------+--------+------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> call t10(2);
+------+--------+------+--------+
| id   | name   | sex  | scores |
+------+--------+------+--------+
|    2 | 李四   ||   85.5 |
+------+--------+------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> call t10(19);
+------+--------+------+--------+
| id   | name   | sex  | scores |
+------+--------+------+--------+
|    1 | 张三   ||   90.5 |
|    2 | 李四   ||   85.5 |
|    3 | 王五   ||   78.5 |
|    4 | 马六   ||   66.5 |
|    5 | 刘七   ||   50.5 |
|    6 | 李九   ||   30.5 |
+------+--------+------+--------+
6 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Example 5

while 的中文是“当....时”,所以,这种方式说的是当 条件成立
时,就进行循环,直到条件不成立才停止

Use the while loop statement to calculate 1+1+2…100

mysql> delimiter ##
mysql> create procedure t11()
    -> begin
    -> declare i int; #定义i为int类型
    -> declare summary int;
    -> set i=1;
    -> set summary=0;
    -> while i <=100 do
    -> set summary=summary+i;
    -> set i=i+1;
    -> end while;
    -> select summary;
    -> end ##
Query OK, 0 rows affected (0.01 sec)

mysql> delimiter ;
mysql> call t11();
+---------+
| summary |
+---------+
|    5050 |
+---------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Example 6
Calculate only even numbers

mysql> create procedure t12(in a int)
    -> begin
    -> declare i int;
    -> declare summary int;
    -> set i=1;
    -> set summary=0;
    -> while i <=a do
    -> if i%2=0 then
    -> set summary=summary+i;
    -> end if;
    -> set i=i+1;
    -> end while;
    -> select summary;
    -> end ##
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;

//The following is equal to only counting even numbers, 2+4+6+8+10

mysql> call t12(10);
+---------+
| summary |
+---------+
|      30 |
+---------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Example 7
Use the while statement to insert 100 pieces of data into the student table

mysql> delimiter ##
mysql> create procedure t13()
    ->     begin
    ->     declare a int;
    ->     set a=0;
    ->     while a<100 do
    ->     insert into student values(a,"a",'未知',100);
    ->     set a=a+1;
    ->     end while;
    ->     end ##
Query OK, 0 rows affected (0.01 sec)

mysql> delimiter ;

Three, view the stored procedure

(1) View which stored procedures exist in the database

mysql> show procedure status\G

You can also use like filtering

mysql> show procedure status like't10'\G
*************************** 1. row ***************************
                 Db: mytest
               Name: t10
               Type: PROCEDURE
            Definer: root@localhost
           Modified: 2020-12-25 17:47:32
            Created: 2020-12-25 17:47:32
      Security_type: DEFINER
            Comment: 
character_set_client: utf8
collation_connection: utf8_general_ci
 Database Collation: utf8_general_ci
1 row in set (0.00 sec)

(2) View the specific information of the stored procedure

mysql> show  create procedure t1\G
*************************** 1. row ***************************
          Procedure: t1
           sql_mode: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
   Create Procedure: CREATE DEFINER=`root`@`localhost` PROCEDURE `t1`()
begin
    create table tt1 (id int,name varchar(30));
    end
character_set_client: utf8
collation_connection: utf8_general_ci
 Database Collation: utf8_general_ci
1 row in set (0.00 sec)

Four, MySQL modify the stored procedure (ALTER PROCEDURE)

The syntax format is as follows:

ALTER PROCEDURE <过程名> [ <特征>]
提示:这个语法用于修改存储过程的某些特征,如要修改存储过程的内容,可以先删除该存储过程,再
重新创建

Modify the content and name of the stored procedure. Modify the content of the stored procedure by deleting the original stored procedure and then creating a new stored procedure with the same name.

Five, delete the stored procedure

Syntax format:

DROP {
    
     PROCEDURE | FUNCTION } [ IF EXISTS ] <过程名>

Note: Before deleting, you must confirm that the stored procedure does not have any dependencies, otherwise it will cause other stored procedures associated with it to fail to run.

mysql> drop procedure if exists t1;
Query OK, 0 rows affected (0.00 sec)

Guess you like

Origin blog.csdn.net/weixin_45310323/article/details/111649340