当前位置:网站首页>[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 luck

This 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 ️
 Insert picture description here



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 .

 Insert picture description here


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
);

 Insert picture description here
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 :
 Insert picture description here


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 :
 Insert picture description here

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 :
 Insert picture description here

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;

 Insert picture description here

(2) View a global variable :

SELECT @@global.auto_increment_increment;

 Insert picture description here
(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)

 Insert picture description here
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;

 Insert picture description here

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;

 Insert picture description here


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);

 Insert picture description here

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);

 Insert picture description here


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 :

  1. func_name: The name of the storage function ;
  2. 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 ;
  3. RETURNS type: Specifies the type of return value ;
  4. characteristic: optional , Specify the properties of the storage function ;
  5. 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 !
 Insert picture description here

Mutual encouragement :“ You make intermittent efforts and muddle through , It's all about clearing the previous efforts .”
 Insert picture description here

原网站

版权声明
本文为[Xiaohuang Xiaohuang is no longer confused]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060811423074.html