当前位置:网站首页>MySQL stored procedure
MySQL stored procedure
2022-06-13 05:56:00 【A programmer in a wig】
Preface
MySQL 5.0 The version starts to support stored procedures .
stored procedure (Stored Procedure) It's a complex program stored in a database , A database object that can be called by an external program .
Stored procedures are designed to accomplish specific functions SQL Statements set , Compiled, created and stored in a database , The user can specify the name of the stored procedure and give the parameters ( When needed ) To call execution .
Stored procedures are very simple in mind , Database SQL Language level code encapsulation and reuse .
advantage
- Stored procedures can be encapsulated , And hide complex business logic .
- Stored procedures can return values , And can accept parameters .
- Stored procedures cannot be used SELECT Command to run , Because it's a subroutine , And view table , Data tables or user-defined functions are different .
- Stored procedures can be used for data validation , Enforce business logic, etc .
shortcoming
- stored procedure , Often customized to a specific database , Because the supported programming languages are different . When switching to the database system of other manufacturers , You need to rewrite the original stored procedure .
- Performance tuning and writing of stored procedures , Limited by various database systems .
First example
We use a simple example to learn the basic syntax of stored procedures
Basic grammar :
CREATE PROCEDURE produce_name( parameter list )
beign -- Indicates the beginning of the process body --
-- Here is your business logic code --
end -- Indicates the end of the process body --
Case study :
Let me start with a few questions , What I use here is Navicat.Navicat The default statement end symbol in is “;” But in a stored procedure, we may have multiple statements , Every statement ends with “;”, To prevent the creation of stored procedures Navicat Just use “;” As a closing sign , We need to restate the closing symbol :
DELIMITER $$
or
DELIMITER //
tips : Of course, you can define this symbol yourself ( Don't be too casual ).
Come on ! Look at the case :
-- Declaration end symbol --
DELIMITER $$
CREATE PROCEDURE PROC_SELECT_BOO()
BEGIN -- Start --
SELECT * FROM book;
END $$ -- end --
-- After declaring the end symbol back --
DELIMITER ;
After execution, view the structure viewport on the left :
Execute stored procedures :
CALL PROC_SELECT_BOO;
Delete stored procedure :
DROP PROCEDURE PROC_SELECT_BOOK
Of course, the stored procedure above just executes a query statement .
There can be business logic in stored procedures , Then basic process control is required .
So we have to write a certain quality of stored procedures , You need to understand some basic syntax of stored procedures .
tips: As long as you have learned programming , It's all very simple .
Of course , What makes us sick is , The syntax of stored procedures in each different database is different . This is also the biggest drawback of stored procedures mentioned earlier .
Basic grammar
Variable
MySQL The variables of are : Global variables , Call back variables , User variables , System variables , local variable .
Here we focus on the use of stored procedures , For the time being, only local variables .
Local variables are declared in BEGIN and END Between variables , The scope is in BEGIN and END Between .
Declare variables : Use DECLARE keyword
DECLARE var_name var_type [default_value]
Case study :
CREATE PROCEDURE PROC_SELECT_BOOK()
BEGIN -- Start --
-- Declare variables v_bookid And the default value is 1 --
DECLARE v_bookid int default 1;
-- Use variables as query criteria --
SELECT * FROM book where bookid = v_bookid;
END $$ -- end --
There are two ways to assign values to variables :
The way 1: direct set
set v_bookid = 1;
The way 2: Use select into
select count(*) into v_count from book
Case study :
- Local variables must be placed at the beginning of the stored procedure
-- Declaration end symbol --
DELIMITER $$
CREATE PROCEDURE PROC_SELECT_BOOK()
BEGIN -- Start --
-- Declare variables v_bookid And the default value is 1 --
DECLARE v_bookid int default 0;
DECLARE v_count int;
-- Use set Assign a value to a variable --
SET v_bookid = 1;
-- Use select into Assign a value to a variable --
SELECT count(*) into v_count FROM book where bookid = v_bookid;
END $$ -- end --
-- After declaring the end symbol back --
DELIMITER ;
Flow control statement
Branch statement
[1] if…then …else
grammar
-- Only if Structure --
if Conditions then
Executed statement
end if;
--if.. else --
if Conditions then
if sentence
else
else sentence
end if;
-- Multiple branches --
if Conditions then
if sentence
elseif Conditions then
sentence ...
.....
else
else sentence
end if;
Case study :
DELIMITER $$
CREATE PROCEDURE PROC_DEMO()
BEGIN
DECLARE v_num int;
set v_num = ROUND(RAND() * 10);
IF MOD(v_num,2)=0 THEN
select ' even numbers ';
elseif MOD(v_num,3) = 0 THEN
select '3 Multiple ';
else
select ' Odd number ';
end if;
END $$
DELIMITER ;
[2]CASE structure
Serve directly :
DELIMITER $$
CREATE PROCEDURE PROC_DEMO()
BEGIN
DECLARE v_num int;
set v_num = ROUND(RAND() * 10);
CASE v_num
when MOD(v_num,2)=0 THEN
select ' even numbers ';
when MOD(v_num,3)=0 THEN
select '3 Multiple ';
else
select ' Odd number ';
end case;
END $$
DELIMITER ;
Loop statement
[1]while ···· end while
while Conditions do
-- The loop body
endwhile
DELIMITER $$
CREATE PROCEDURE PROC_DEMO()
BEGIN
DECLARE v_num int default 0;
while v_num < 10 do
insert into temp values(v_num);
set v_num = v_num + 1;
end while;
END $$
DELIMITER ;
[2]repeat···· end repeat
repeat
-- The loop body
until The loop condition
end repeat;
DELIMITER $$
CREATE PROCEDURE PROC_DEMO()
BEGIN
DECLARE v_num int default 0;
repeat
insert into temp values(v_num);
set v_num = v_num + 1;
until v_num >= 10 end repeat;
END $$
DELIMITER ;
[3]loop ·····endloop
loop The loop does not require initial conditions , This and while Cyclic similarity , At the same time with repeat There is no end condition for a loop , leave The meaning of a sentence is to leave a loop .
DELIMITER $$
CREATE PROCEDURE PROC_DEMO()
BEGIN
DECLARE v_num int default 0;
LOOP_LABLE:loop
insert into temp values(v_num);
set v_num = v_num + 1;
if v_num >=10 then
leave LOOP_LABLE;
end if;
end loop;
END $$
DELIMITER ;
Parameters of stored procedure
MySQL Parameters of stored procedure are used in the definition of stored procedure , There are three types of parameters ,IN,OUT,INOUT, In the form of :
CREAT EPROCEDURE Stored procedure name ([[IN |OUT |INOUT ] Parameter name Data classes ...])
- IN Input parameters : Indicates that the caller passes a value... To the procedure ( The incoming value can be literal or variable )
- OUT Output parameters : Indicates that the procedure passes out a value to the caller ( Multiple values can be returned )( Outgoing values can only be variables )
- INOUT Input/output parameter : It means that the caller passes in a value to the procedure , It also indicates that the procedure passes out a value to the caller ( Values can only be variables )
1、in Input parameters
It can be simply understood as java Method parameters
delimiter $$
create procedure in_param(in p_in int)
begin
select p_in;
set p_in=2;
select P_in;
end $$
delimiter ;
forehead ~~~~
To call a stored procedure with input parameters, you need to pass in the corresponding parameters
call in_param(100);
2、out Output parameters
Simply understood as java The return value of the method in
delimiter $$
create procedure out_param(out p_out int)
BEGIN
select p_out;
set p_out = 10000;
select p_out;
end $$
delimiter ;
Call a stored procedure with output parameters
-- there @p_out Is a user variable --
set @p_out=1;
call out_param(@p_out);
select @p_out;
3、inout Input parameters
forehead !!! Literally . Can input , It can also output . In fact, it's good to know , Try not to use this type of parameter
delimiter $$
create procedure inout_param(out p_inout int)
BEGIN
select p_inout;
set p_inout = 10000;
select p_inout;
end $$
delimiter ;
call
set @p_inout=1;
call inout_param(@p_inout);
select @p_inout;
边栏推荐
- @The detailed explanation of configurationproperties and the problem that all properties of the entity bean modified by this annotation are null after injection are solved
- 1 Introduction to drools rule engine (usage scenarios and advantages)
- Leetcode- reverse vowels in string - simple
- 13 cancelendevent of a flowable end event and compensationthrowing of a compensation event
- Leetcode- maximum average of subarray i- simple
- Etcd understanding of microservice architecture
- 9. Errorstartevent and errorboundaryevent of error events
- 3. Postman easy to use
- 中断处理过程
- OpenGL mosaic (VIII)
猜你喜欢
![[turn] explain awk (1)__ Awk Basics_ Options_ Program segment parsing and examples](/img/65/a214d137e230b1a1190feb03660f2c.jpg)
[turn] explain awk (1)__ Awk Basics_ Options_ Program segment parsing and examples

AUTOSAR actual combat tutorial pdf version

A simple recursion problem of linked list

NVIDIA Jetson Nano/Xavier NX 扩容教程

軟件測試——接口常見問題匯總

Zero copy technology

Building a stand-alone version of Nacos series

2021.9.30 learning log -postman

10 signalstartevent and signalcatchingevent of flowable signal events
![[China & some provinces and cities] JSON file for offline map visualization](/img/ea/0c552e1e133f693b9902c54c2e09c8.jpg)
[China & some provinces and cities] JSON file for offline map visualization
随机推荐
Sentinel series integrates Nacos and realizes dynamic flow control
2021-9-19
软件测试——接口常见问题汇总
Quartz basic use
Leetcode- detect uppercase letters - simple
19 calling subprocess (callactivity) of a flowable task
Hump naming and underlining
Explanation of sentinel series' features, composition and deployment
Parallelgateway and exclusivegateway of 14 gateways
Leetcode- longest palindrome string - simple
Randomly fetch data from the list
The 13th week of the second semester of sophomore year
2021.9.29学习日志-MIME类型
Power of leetcode-4 - simple
中断处理过程
AUTOSAR actual combat tutorial pdf version
arrayList && linkedList
Class conflicts caused by tongweb Enterprise Edition and embedded Edition
Missing tag identification in cots RFID systems: bringing the gap between theory and Practice
The SQL file of mysql8.0 was imported into version 5.5. There was a pit