15. Stored procedure

1. Introduction
Stored Procedure (Stored Procedure) is a set of SQL statements in order to complete a specific function. It is compiled and saved in the database. The user can call and execute it by specifying the name of the stored procedure and given parameters, similar to the programming language Method or function.

2. Advantages
Reusability: The stored procedure is an encapsulation of SQL statements, supports receiving parameters, and returns the operation results, which can enhance the reusability.
Logic: Stored procedures can hide complex business logic and business logic.

3. Disadvantages
Portability: The portability of the stored procedure is poor. If the database is replaced, the stored procedure must be rewritten.
Scalability: The stored procedure is difficult to debug and expand.

4. Grammar

#存储过程定义
delimiter //
create procedure procedureName(入参,出参)
begin
   存储过程;
end
// 
delimiter ;

#存储过程调用
call procedureName(入参,出参);

5. Stored procedure example: find the sum of two numbers

delimiter //
create procedure my_sum(in a int, in b int, out result int) 
begin
   set result = a + b; 
end
// 
delimiter ;

call my_sum(10, 20, @result); 
select @result;

Insert picture description here

6. Example of a stored procedure: Calculate the sum of 1+2+…+n

delimiter //
create procedure my_n_sum(in n int, out result int) 
begin
   declare i int default 1; declare sum int default 0;
   while i<=n do
   set sum = sum + i; set i = i + 1;
   end while;
   set result = sum; 
end;
// 
delimiter ;

call my_n_sum(10, @result); 
select @result;

Insert picture description here

Guess you like

Origin blog.csdn.net/Jgx1214/article/details/107496197