mysql: the creation and use of stored procedures

1. Create a stored procedure

When using MySql Workbench to create a stored procedure, be sure to use delimiter to specify the terminator, otherwise an error will be reported: Statement is incomplete, expecting: ';'

Error example:

create procedure area_pro1(in mylevel tinyint)
begin
	select * from area_code_2022 where level= mylevel ;
end;

Correct example:

delimiter //
create procedure area_pro1(in mylevel tinyint)
begin
	select * from area_code_2022 where level= mylevel ;
end
//

Among them, // is the terminator, which can be specified by yourself, for example, $$ is generally used.

Second, stored procedure syntax

I won’t copy the official grammar here, let’s talk about it according to my understanding:

create procedure 存储过程名(in/out/inout 参数名  参数类型)
begin
	存储过程体,也就是你想执行什么逻辑 ;
end

Among them, in represents an input parameter, out represents an output parameter, and inout can be either an input or an output.

Third, the use of stored procedures

1. To use a stored procedure with only input parameters, use: call stored procedure name (value) .

Note: If the stored procedure does not pass parameters or passes the wrong parameter type, the stored procedure will report an error. Whether this parameter can be passed is not yet confirmed. If you are sure, please leave a message in the comment area.

2. Stored procedures using output parameters

delimiter //
create procedure area_pro2(out myResult varchar(20000))
begin
select name into myResult from area_code_2022 where level=1 ;
end 
//

With into, the outgoing content is assigned to the parameter.

Call, pay attention to the @ symbol

 3. inout can be used both as an input parameter and as an output parameter, so I won’t say too much here.

Fourth, it is generally not recommended to use stored procedures

1. Advantages

1. Compile once, run multiple times, with good performance, saving compilation time for each run

2. Prevent sql injection attacks

3. Hide the complexity of the database and encapsulate the process of array assembly

2. Disadvantages

1. Stored procedures are difficult to debug

2. The portability is poor. When the type of data is switched, the stored procedure will basically stop.

3. If the business data model changes, the stored procedure must be changed together with the business code

Note: Of course, this statement is generally a rhetoric on the Internet, and I have not used it in actual projects myself. However, it is said that mysql does not optimize the debugging of stored procedures well, and sqlserver seems to be okay.

Guess you like

Origin blog.csdn.net/weixin_44431073/article/details/128647071