MySQL---Detailed explanation of stored procedures

Introduction to stored procedures

Why use stored procedures?

MySQL 5.0 version began to support stored procedures.

Most SQL statements are single statements against one or more tables. Not all operations are that simple. Often a complete operation requires multiple statements to complete.

Simply put, a stored procedure is a collection of one or more MySQL statements that are saved for later use. Think of it as a batch file. Although their role is not limited to batch processing.

The stored procedure is very simple in thought, that is, code encapsulation and reuse at the database SQL language level.

Advantages of stored procedures

  1. Simplify complex operations by encapsulating the processing in easy-to-use units;
  2. Simplify the management of changes. If the table name, column name or business logic changes. Only need to change the code of the stored procedure, the people who use it will not change their own code;
  3. Usually stored procedures help improve the performance of the application. When the created stored procedure is compiled, it is stored in the database. However, the stored procedures implemented by MySQL are slightly different. MySQL stored procedures are compiled on demand. After compiling the stored procedure, MySQL puts it in the cache. MySQL maintains its own stored procedure cache for each connection. If the application uses the stored procedure multiple times in a single connection, use the compiled version, otherwise the stored procedure works like a query;
  4. Stored procedures help to reduce the traffic between the application and the database server, because the application does not have to send multiple lengthy SQL statements, but only the name and parameters of the stored procedure;
  5. The stored program is reusable and transparent to any application. The stored procedure exposes the database interface to all applications, so that developers do not need to develop the supported functions in the stored procedure;
  6. The stored program is safe. Database administrators can grant appropriate permissions to applications that access stored procedures in the database without providing any permissions to the underlying database tables.

Disadvantages of stored procedures

  1. If a large number of stored procedures are used, the memory usage of each connection that uses these stored procedures will greatly increase. In addition, if you overuse a large number of logical operations in the storage process, the CPU usage will also increase, because the initial design of the MySQL database focuses on efficient queries, which is not conducive to logical operations;
  2. The structure of stored procedures makes it more difficult to develop stored procedures with complex business logic;
  3. It is difficult to debug stored procedures. Only a few database management systems allow you to debug stored procedures. Unfortunately, MySQL does not provide the ability to debug stored procedures;
  4. It is not easy to develop and maintain stored procedures. Developing and maintaining stored procedures usually requires a professional skill that not all application developers have. This may cause problems in the application development and maintenance phase.

Stored procedures in MySQL

Create and call procedures

Create a stored procedure, the code is as follows:

-- 创建存储过程 
create procedure mypro(in a int,in b int,out sum int) 
begin 
set sum = a+b; 
end;

The results are as follows

image-20210316103451673

You can also view the process under the "Function" node of the Navicat client, as shown in the figure below:

image-20210316103523273

Call the stored procedure, the code is as follows:

call mypro(1,2,@s);-- 调用存储过程 
select @s;-- 显示过程输出结果

operation result

image-20210316103610471

Stored procedure syntax analysis

  • create procedure Used to create the process;
  • mypro Used to define the process name;
  • (in a int,in b int,out sum int)Parameter represents the process in which indenotes an input parameter, outindicates an output parameter. Similar to the formal parameters and return value when Java defines a method;
  • beginAnd endrepresents the beginning and end of the main body of the process, which is equivalent to a pair of curly braces in a Java definition method;
  • callUsed to call the process, @sis the variable used to receive the process output parameters

Parameters of the stored procedure

The parameters of the MySQL stored procedure are used in the definition of the stored procedure. There are three types of parameters:

  • IN Input parameter: indicates that the caller passes in a value to the procedure (the incoming value can be a literal or variable);
  • OUT Output parameter: indicates that the process sends out a value to the caller (multiple values ​​can be returned) (the outgoing value can only be a variable);
  • INOUTInput and output parameters: It not only means that the caller passes in a value to the process, but also means that the process passes a value to the caller (the value can only be a variable).

Stored procedures can be divided into four categories according to parameters:

1). Process without parameters;

2). Only the process of inputting parameters;

3). Only the process of output parameters;

4). Process including input and output parameters.

variable

The stored procedure in MySQL is similar to the method in java.

In this case, variables can also be used in stored procedures. The local variable scope in java is the method where the variable is located, while the local variable scope in MySQL is the stored procedure where it is located.

Variable definitions

DECLARE variable_name [,variable_name...] datatype [DEFAULT value];
  • declareUsed to declare variables;

  • variable_nameRepresents the variable name;

  • datatypeIs the data type of MySQL;

  • defaultUsed to declare default values;

  • E.g:

    declare name varchar(20) default ‘jack’。
    

Variable assignment

SET 变量名 = 表达式值 [,variable_name = expression ...]

Use variables in the stored procedure, the code is as follows

use schooldb;-- 使用 schooldb 数据库
-- 创建过程
create procedure mypro1()
begin
declare name varchar(20);
set name = '丘处机';
select * from studentinfo where studentname = name;
end;
-- 调用过程
call mypro1();

operation result

image-20210316104419334

Flow control statement

if conditional statement

IFThe statement contains multiple conditional judgments. According to the result TRUE, FALSEthe statement is executed if, else ifwhich is elsesimilar to the syntax of,, and in programming languages .

Define a stored procedure, enter an integer, and use the if statement to determine whether it is positive or negative. The code is as follows:

-- 创建过程
create procedure mypro2(in num int)
begin
if num<0 then -- 条件开始
select '负数';
elseif num=0 then
select '不是正数也不是负数';
else
select '正数';
end if;-- 条件结束
end;
-- 调用过程
call mypro2(-1);

operation result

image-20210316104810016

case conditional statement

caseIt is another conditional statement, similar to the programming language choose, whensyntax. In MySQL casestatement has two syntax
formats.

Define a stored procedure, enter an integer, and use the case statement to determine whether it is positive or negative. The code is as follows:

-- 创建过程
create procedure mypro3(in num int)
begin
case -- 条件开始
when num<0 then select '负数';
when num=0 then select '不是正数也不是负数';
else select '正数';
end case; -- 条件结束
end;
-- 调用过程
call mypro3(1);

operation result

image-20210316104934579

Define a stored procedure, enter an integer, and use the case statement to determine whether it is 1 or 2. The code is as follows:

-- 创建过程
create procedure mypro4(in num int)
begin
case num -- 条件开始
when 1 then select '数值是 1';
when 2 then select '数值是 2';
else select '不是 1 也不是 2';
end case; -- 条件结束
end;
-- 调用过程
call mypro4(3);

operation result

image-20210316105009743

Both case syntaxes can implement conditional judgments, but the first is suitable for range value judgments, and the second is suitable for definite value judgments.

while loop statement

whileUsage statement and javain whilea similar cycle.

Define a stored procedure and use a while loop to output the cumulative sum of 1 to 10. The code is as follows:

-- 创建过程
create procedure mypro5(out sum int)
begin
declare num int default 0;
set sum = 0;
while num<10 do -- 循环开始
set num = num+1;
set sum = sum+num;
end while; -- 循环结束
end;
-- 调用过程
call mypro5(@sum);
-- 查询变量值
select @sum;

operation result

image-20210316105127457

repeat loop statement

repeatUsage and statements javain the do…whilestatement, the operations are the first execution cycle, then the determination condition, the difference between repeatthe expression of
the formula is falseonly executed loops until the value of the expression trueis stopped.

Define a stored procedure and use a repeat loop to output the cumulative sum of 1 to 10. The code is as follows:

-- 创建过程
create procedure mypro6(out sum int)
begin
declare num int default 0;
set sum = 0;
repeat-- 循环开始
set num = num+1;
set sum = sum+num;
until num>=10
end repeat; -- 循环结束
end;
-- 调用过程
call mypro6(@sum);
-- 查询变量值
select @sum;

operation result

image-20210316105241308

loop statement

Loop statements are used to execute certain statements repeatedly.

May be used during execution leavestatement or iterateout of the loop may be nested IFlike judgment statement.

  • leaveThe effect of the statement is equivalent to that in java, breakwhich is used to terminate the loop;
  • iterateThe effect of the statement is equivalent to that in java, continuewhich is used to end this loop operation and enter the next loop.

Define a stored procedure and use loop to output the cumulative sum of 1 to 10. The code is as follows:

-- 创建过程
create procedure mypro7(out sum int)
begin
declare num int default 0;
set sum = 0;
loop_sum:loop-- 循环开始
set num = num+1;
set sum = sum+num;
if num>=10 then
leave loop_sum;
end if;
end loop loop_sum; -- 循环结束
end;
-- 调用过程
call mypro7(@sum);
-- 查询变量值
select @sum;

operation result

image-20210316105416021

The loop_sum in the code is equivalent to labeling the loop to facilitate flexible operation during multiple loops.

Management of stored procedures

The management of the storage process mainly includes: display the process, display the source code of the process, and delete the process.

The simpler way is to use the Navicat client tool for management, just click the mouse, as shown in the figure below:

image-20210316105545505

Show stored procedure

SHOW PROCEDURE STATUS;

Display the stored procedures of a specific database

SHOW PROCEDURE status where db = 'schooldb';

To display stored procedures in a specific mode, it is required to display stored procedures with "my" in the name

SHOW PROCEDURE status where name like '%my%';

Display the source code of the stored procedure "mypro1"

SHOW CREATE PROCEDURE mypro1;

image-20210316105740141

Delete the stored procedure "mypro1"

drop PROCEDURE mypro1;

Guess you like

Origin blog.csdn.net/whf_a/article/details/114871866