当前位置:网站首页>[MySQL] database stored procedure and storage function clearance tutorial (full version)
[MySQL] database stored procedure and storage function clearance tutorial (full version)
2022-07-06 08:20:00 【Xiaohuang Xiaohuang is no longer confused】
Personal home page : Huang Xiaohuang's blog home page
️ Stand by me : give the thumbs-up Collection Focus on
Maxim : Only one step at a time can we accept the so-called luckThis article is from the column :MySQL8.0 Learning notes
This article refers to the video :MySQL Database complete tutorial
Welcome to the support subscription column ️
List of articles
1 Overview of stored procedures
brief introduction :
from MySQL5.0 Stored procedures have been supported since version . Simply speaking , A stored procedure is a set of SQL Statements set , Powerful , It can realize some complex logic functions , similar Java The method in . Stored procedures are databases SQL Language level code encapsulation and reuse .
characteristic :
- There are input and output parameters , You can declare variables , There are also cycles 、 Select control statement , By writing stored procedures , It can realize complex logic functions ;
- It has the general characteristics of functions : modularization 、 encapsulation 、 Code reuse ;
- Fast , Only the first execution needs to go through the compilation and optimization steps , Subsequent calls can be executed directly .
2 Quick start to stored procedures
The syntax format for defining stored procedures is as follows :
delimiter Custom end symbol
create procedure Storage name ([in, out, inout] Parameter name data type ...)
begin
sql sentence
end Custom end symbol
delimiter;
Before working on the example , First, prepare the data , The construction code of the table is as follows , The result is shown in Fig. :
create table student
(
sid int null,
name varchar(20) null,
gender varchar(20) null,
age int null,
birth date null,
address varchar(20) null,
score double null
);
The following code defines a stored procedure , The query score is higher than 90 branch ( contain 90 branch ) Students' names and scores , See code comments for details :
When defining stored procedures , Custom closing symbols are often used $$ perhaps //
-- Define stored procedures
DELIMITER $$
CREATE PROCEDURE protest01()
BEGIN
SELECT name, score FROM student WHERE score >= 90;
end $$
DELIMITER ;
-- Calling stored procedure
CALL protest01();
give the result as follows :
3 Variable
3.1 local variable
Local variables are user-defined , Only in begin/end It works in blocks , Its The syntax is as follows :
declare var_name type [default var_value];
️ The operation sample :
In the following code , Stored procedures define variables name, And changed its value , Last query .
DELIMITER $$
CREATE PROCEDURE protest02()
BEGIN
DECLARE name VARCHAR(20) DEFAULT 'nezuko';
SET name = ' Huang Xiaohuang ';
SELECT name;
end $$
DELIMITER ;
CALL protest02();
give the result as follows :
3.2 User variables
User variables are also user-defined , In the current connection ( conversation ) Effective in , By analogy Java Member variables in . Define user variables The syntax is as follows :
@var_name -- Use to declare
️ The operation sample :
User variables are defined in the following code @student_name, And try at begin/end Use outside the code block .
DELIMITER $$
CREATE PROCEDURE protest03()
BEGIN
SET @student_name = ' Huang Xiaohuang '; -- Define user variables
end $$
DELIMITER ;
SELECT @student_name; -- Can be in begin/end External use of user variables
give the result as follows :
3.3 System variables
Introduction to system variables :
- System variables are divided into global variables and session variables ;
- The global variable is in MySQL At startup, the server automatically initializes them to the default value , These default values can be changed through customs my.ini Folder changes ;
- Session variables are used every time a new connection is established , from MySQL To initialize the .MySQL Copies the values of all current global variables , Used as session variables ;
- If the session variable is established , There is no manual modification of the values of session variables and global variables , Then the values of these variables are the same ;
- The difference between global variables and session variables is , The modification of global variables will affect the entire server , But the modification of session variables , It only affects the current conversation ( Current database connection );
- The values of some system variables can be dynamically modified by customs clearance statements , But some system variables are read-only , For changeable system variables, use SET Statement changes .
3.3.1 Global variables
Provided by the system , Valid throughout the database , The syntax is as follows :
@@global.var_name
️ The operation sample :
(1) View global variables :
SHOW GLOBAL variables;
(2) View a global variable :
SELECT @@global.auto_increment_increment;
(3) Modify the value of the global variable :
-- The way 1
SET GLOBAL variable_name = xxxxx;
-- The way 2
SET @@global.variable_name = xxxxx;
3.3.2 Session variables
Provided by the system , The current session is valid . The syntax is as follows :
@@session.var_name;
️ The operation sample :
Similar to global variables , It's just a little different , Here's the code directly .
-- 1. View session variables
SHOW SESSION variables;
-- 2. View a session variable
SELECT @@session.auto_increment_increment;
-- 3. Modify the value of the session variable
-- The way 1
SET SESSION variable_name = xxxxx;
-- The way 2
SET @@session.variable_name = xxxxx;
4 Parameter passing in stored procedures
4.1 Parameter passing —in
in Represents the parameter passed in , You can pass in values or variables , Even if you pass in a variable , It will not change the value of the variable . It can be changed internally , But it only works inside the function .
Example :
Encapsulate a stored procedure with parameters param01, Pass in the student number , Search for student information , The code is as follows :
DELIMITER $$
CREATE PROCEDURE param01(IN student_no INT)
BEGIN
SELECT * FROM student WHERE sid = student_no;
end $$
DELIMITER ;
CALL param01(3)
It should be noted that , Try not to keep the parameter name consistent with the name to be queried , In the stored procedure , Keep the principle of proximity , That is, if the parameter and attribute have the same name , Interpreted as parameters in stored procedures !
4.2 Parameter passing —out
out Indicates that a value is passed from within the stored procedure to the caller .
Example :
Encapsulate a stored procedure with parameters , Pass in the student ID and return the student name , The sample code is as follows :
DELIMITER $$
CREATE PROCEDURE param02(IN student_no INT, OUT out_name VARCHAR(20))
BEGIN
SELECT name INTO out_name FROM student WHERE sid = student_no;
end $$
DELIMITER ;
CALL param02(2, @o_name);
SELECT @o_name;
4.3 Parameter passing —inout
inout Represents a variable that can be returned by a modified parameter passed in from outside , You can use the values passed into the table , You can also modify the value of the variable ( Even if the function is executed ).
Example :
In the following code , Parameters num In the stored procedure, it is modified to num+100:
DELIMITER $$
CREATE PROCEDURE param03(INOUT num INT)
BEGIN
SET num = num+100;
end $$
DELIMITER ;
SET @num = 30;
CALL param03(@num);
SELECT @num;
5 Process control
5.1 Process control — Judge
IF The statement contains multiple judgment conditions , According to the result TRUE And FALSE Execute statement , The syntax is as follows :
IF search_condition_1 THEN statement_list_1
[ELSEIF search_condition_2 THEN statement_list_2]
[ELSE search_condition_n]
END IF;
Example :
The stored procedure in the following code , The judgment grade of the result is simulated :
DELIMITER $$
CREATE PROCEDURE test_if(IN score DOUBLE)
BEGIN
IF score < 60 THEN
SELECT ' fail, ';
ELSEIF score < 75 THEN
SELECT ' pass ';
ELSEIF score < 85 THEN
SELECT ' good ';
ELSE
SELECT ' good ';
END IF;
END $$
DELIMITER ;
CALL test_if(90);
5.2 Process control —case
CASE Similar to... In programming languages switch grammar . The syntax is as follows :
-- Grammar 1
case case_value
when when_value then statement_list;
[when when_value then statement_list;]
[else statement_list;]
end case;
-- Grammar II
case
when search_condition then statement_list;
[when search_condition then statement_list;]
[else statement_list;]
end case;
5.3 Process control — loop
summary :
- A loop occurs only once in a program , However, code may run multiple times in a row ;
- The code of the loop will run a certain number of times , Or run until the end of a specific condition .
️ classification :
- while
- repeat
- loop
️ Cycle control :
- leave similar break;
- iterate similar continue.
5.3.1 while
Grammar format :
【 label :】while The loop condition do
The loop body
end while【 label :】
️ The operation sample :
Create an action table test, Contains two properties ( Student number 、 user name ), Define a stored procedure to add n Data , Test data n=10. Reference code and results :
-- 1 Create table
CREATE TABLE IF NOT EXISTS test(
id INT,
username VARCHAR(10)
);
-- 2 Define stored procedures
DELIMITER $$
CREATE PROCEDURE myinsert(IN insert_count INT)
BEGIN
DECLARE i INT DEFAULT 1;
lable:WHILE i <= insert_count DO
INSERT INTO test VALUES (i, concat('user', i));
SET i = i + 1;
END WHILE lable;
end $$
DELIMITER ;
-- 3 Calling stored procedure
CALL myinsert(10);
5.3.2 repeat
Be similar to do-while loop , The format is as follows :
【 label :】repeat
The loop body ;
until Conditional expression
end repeat【 label 】;
5.3.3 loop
Generally, it is still used while loop , More concise .
Grammar format :
【 label :】loop
The loop body ;
if Conditional expression then
leave 【 label 】
end if;
end loop;
6 The cursor
The cursor (cursor) Is the data type used to store the query result set , In stored procedures and functions, cursors can be used to cycle the result set . The use of cursors includes declarations 、open、fetch、close.
Grammar format :
-- Statement
declare cursor_name cursor for select_statement;
-- open
open cursor_name;
-- Value
fetch cursor_name into var_name [, var_name]...;
-- close
close curcor_name;
Demonstrate the use of cursors :
Enter a student number , Query student name and address information .
DELIMITER $$
CREATE PROCEDURE search(IN student_no INT)
BEGIN
DECLARE student_name VARCHAR(20);
DECLARE student_address VARCHAR(20);
-- 1 declare cursor
DECLARE my_cursor CURSOR FOR
SELECT name, address FROM student WHERE sid = student_no;
-- 2 Open cursor
OPEN my_cursor;
-- 3 Value
FETCH my_cursor INTO student_name, student_address;
SELECT student_name full name , student_address Address ;
-- 4 close
CLOSE my_cursor;
END $$
DELIMITER ;
CALL search(1);
7 exception handling
stay MySQL Exception handling is defined in HANDLER To complete the implementation of exception declaration , The syntax is as follows :
DECLARE handler_action HANDLER
FOR condition_value[, condition_value]...
statement
handler_action:{
CONTINUE
|EXIT
|UNION
}
condition_value:{
mysql_orror_codo
|condition_name
|SQLWARNING
|NOT FOUND
|SQLEXCEPTION
}
For details of exception handling, please refer to relevant official documents .
8 Storage function
Format :
create function func_name ([param_name type[, ...]])
returns type
[characteristic ...]
begin
routine_body
end;
Parameter description :
- func_name: The name of the storage function ;
- param_name type: optional , Specify the parameters of the storage function .type Parameter is used to specify the parameter type of the storage function , The type must be MySQL Supported parameter types ;
- RETURNS type: Specifies the type of return value ;
- characteristic: optional , Specify the properties of the storage function ;
- routine_body:SQL Code content .
The use of stored functions is similar to that of stored procedures , Only the function itself can have a return value , Stored procedures need to use parameters to return values .
It should be noted that , When creating a storage function , Permission to create functions must be allowed to trust , Otherwise you can't create
The code is as follows :
set global log_bin_trust_function_creators = TRUE;
At the end
The above is the whole content of this article , The follow-up will continue Free update , If the article helps you , Please use your hands Point a praise + Focus on , Thank you very much ️ ️ ️ !
If there are questions , Welcome to the private letter or comment area !
Mutual encouragement :“ You make intermittent efforts and muddle through , It's all about clearing the previous efforts .”
边栏推荐
- 在 uniapp 中使用阿里图标
- Epoll and IO multiplexing of redis
- 从 CSV 文件迁移数据到 TiDB
- NFT smart contract release, blind box, public offering technology practice -- jigsaw puzzle
- Configuring OSPF load sharing for Huawei devices
- [research materials] 2021 Research Report on China's smart medical industry - Download attached
- String to leading 0
- 2022 Inner Mongolia latest construction tower crane (construction special operation) simulation examination question bank and answers
- LDAP应用篇(4)Jenkins接入
- CAD ARX gets the current viewport settings
猜你喜欢
Leetcode question brushing record | 203_ Remove linked list elements
【T31ZL智能视频应用处理器资料】
CISP-PTE实操练习讲解
Configuring OSPF load sharing for Huawei devices
"Designer universe": "benefit dimension" APEC public welfare + 2022 the latest slogan and the new platform will be launched soon | Asia Pacific Financial Media
"Friendship and righteousness" of the center for national economy and information technology: China's friendship wine - the "unparalleled loyalty and righteousness" of the solidarity group released th
The State Economic Information Center "APEC industry +" Western Silicon Valley will invest 2trillion yuan in Chengdu Chongqing economic circle, which will surpass the observation of Shanghai | stable
National economic information center "APEC industry +": economic data released at the night of the Spring Festival | observation of stable strategy industry fund
[research materials] 2021 Research Report on China's smart medical industry - Download attached
Personalized online cloud database hybrid optimization system | SIGMOD 2022 selected papers interpretation
随机推荐
升级 TiDB Operator
图像融合--挑战、机遇与对策
Asia Pacific Financial Media | designer universe | Guangdong responds to the opinions of the national development and Reform Commission. Primary school students incarnate as small community designers
Use dumping to back up tidb cluster data to S3 compatible storage
[2022 广东省赛M] 拉格朗日插值 (多元函数极值 分治NTT)
07- [istio] istio destinationrule (purpose rule)
Migrate data from CSV files to tidb
Summary of MySQL index failure scenarios
Golang DNS write casually
Analysis of pointer and array written test questions
Use br to back up tidb cluster data to S3 compatible storage
Understanding of law of large numbers and central limit theorem
TiDB备份与恢复简介
让学指针变得更简单(三)
hcip--mpls
NFT smart contract release, blind box, public offering technology practice -- contract
[research materials] 2022 China yuancosmos white paper - Download attached
Migrate data from a tidb cluster to another tidb cluster
MFC sends left click, double click, and right click messages to list controls
2022 Inner Mongolia latest water conservancy and hydropower construction safety officer simulation examination questions and answers