当前位置:网站首页>MySQL stored procedure + function
MySQL stored procedure + function
2022-06-24 03:29:00 【Kaiyuanjun】
Stored procedures and functions
The article has been synchronized to GitHub Open source project : Java The road of supernatural
Variable
- System variables
- Global variables
- Session variables
Look at all variables
SHOW GLOBAL/SESSION VARIVALES
Conditions of the query
SHOW GLOBAL/SESSION LIKE '%char%'
View the value of a variable
SELECT @@GLOBAL/SESSION. System variable name
Set the value
SET GLOBAL/SESSION. System variable name = value ;
- Custom variable
- User variables
- Scope : The target is valid for the current session
- Use
```sql
SET @ User variable name = value # Declare assignments 1
SELECT Field INTO @ Variable name # Declare assignments 2
SELECT @ Variable name # see
```
- local variable
- Scope : At present begin / end The scope is valid
- Use
```mysql
DECALARE Variable name type ; # Statement
SET Variable name = value ;# assignment
SELECT Variable name ; # see
```
stored procedure
- Concept
A set of precompiled SQL Statement set .
- benefits
- Improve the versatility of the code
- Simplified operation
- Reduced compilation and connection times , Increase of efficiency
- grammar
- establish
```sql
CREATE PROCEDURE Stored procedure name ( parameter list )
BEGIN
SQL sentence 1;
SQL sentence 2;
END
```
- parameter list - Parameter mode IN,OUT,INOUT - Parameter name - Parameter type
- Use
```sql
CALL Stored procedure name ( Argument list );
```
- Example
- Insert into book Five records in
```sql
# Definition
CREATE PROCEDURE INSERT5()
BEGIN
INSERT INTO book values (1,' computer network ',45.9,' Luo Guanzhong ',NOW());
INSERT INTO book values (2,' computer network ',45.9,' Luo Guanzhong ',NOW());
INSERT INTO book values (3,' computer network ',45.9,' Luo Guanzhong ',NOW());
INSERT INTO book values (4,' computer network ',45.9,' Luo Guanzhong ',NOW());
INSERT INTO book values (5,' computer network ',45.9,' Luo Guanzhong ',NOW());
END;
# call
CALL INSERT5();
```
- Query employees according to salary
# Query employees according to salary
CREATE PROCEDURE getBySalary(IN s double)
BEGIN
SELECT *
FROM employees
WHERE salary = s;
END;
# call
CALL getBySAlary();
- Return employee name according to salary
# Definition
CREATE PROCEDURE getNameBySalary(IN salary double,OUT name VARCHAR(20))
BEGIN
SELECT last_name INTO name
FROM employees
WHERE employees.salary = salary;
END;
# call
SET @result;
CALL getNameBySalary(24000,@result);
SELECT @result;
function
There is and only one return
- establish
CREATE FUNCATION Function name ( Parameter name Parameter type , Parameter name Parameter type ) RETURNS Return type
BEGIN
The body of the function
END
- call
SELECT Function name ( parameter list );
Case presentation
- Return without reference
Number of employees returned to the company
```sql
# Definition
CREATE FUNCTION countEmp() RETURNS INT
BEGIN
DECLARE result INT;
SELECT COUNT(*) INTO result
FROM employees;
RETURN result;
END;
# call
SELECT countEmp();
```
- You can go back to
Return salary according to employee name
# Definition
CREATE FUNCTION getSalaryByName(name VARCHAR(20)) RETURNS DOUBLE
BEGIN
DECLARE salary DOUBLE;
SELECT e.salary INTO salary
FROM employees e
WHERE e.last_name = name;
RETURN salary;
END;
# call
SELECT getSalaryByName('K_ing');
- View function definition statements
SHOW CREATE FUNCTION Function name ;
Process control structure
Branching structure
- IF( expression 1, expression 2, expression 3) If the expression 1 establish , return 2, Otherwise return to 3
- CASE structure
If ELSE Omit When they don't match return NULL
# Equivalent judgment
CASE expression / value / Field
WHEN Constant 1 THEN sentence 1;
WHEN Constant 2 THEN sentence 2;
ELSE Default statement ;
END;
# Interval judgment
CASE
WHEN Conditions THEN sentence ;
WHEN Conditions THEN sentence ;
ELSE Default statement ;
END;
Case study : Create a function , According to the incoming grades , Display level
# Definition
CREATE FUNCTION wage_scale(score DOUBLE) RETURNS varchar(10)
BEGIN
CASE
WHEN score>=90 THEN RETURN ' good ';
WHEN score>=80 THEN RETURN ' good ';
WHEN score>=70 THEN RETURN ' Ordinary ';
WHEN score>=60 THEN RETURN ' pass ';
ELSE RETURN ' fail, ';
END CASE;
END;
# call
SELECT wage_scale(90);
Loop structure
WHILE
- grammar
Tag name WHILE The loop condition DO
The loop body ;
END WHILE Tag name ;
Case study : Insert in batches according to the number of times admin Table data
# Define stored procedures
CREATE PROCEDURE pro_while(IN count INT)
BEGIN
DECLARE i INT DEFAULT 1;
WHILE i <= count
DO
INSERT INTO admin (username, password) VALUES (count, count);
SET i = i + 1;
END WHILE;
end;
# call
CALL pro_while(10);
# result admin Insert in table 10 Data
LOOP It can be used to simulate a simple dead cycle
- grammar
Tag name LOOP
The loop body ;
END LOOP Tag name
REPEAT
- grammar
Tag name REPEAT
The loop body ;
UNTIL End cycle condition
END REPEAT Tag name
Case study
Known table content
Field | explain |
|---|---|
id | Since the primary key |
content | Random character |
Create stored procedure , Inserts a specified number of random characters .
# Build table
CREATE TABLE content(
id INT PRIMARY KEY AUTO_INCREMENT,
content VARCHAR(100)
);
# Create stored procedure
CREATE PROCEDURE random_content(IN count INT)
BEGIN
# Defining variables
DECLARE i INT DEFAULT 1;
WHILE i <= count DO
# The loop body
INSERT INTO content VALUES (null,random_bytes(100));
SET i = i+1;
END WHILE;
END;
#d
CALL random_content(100);The article has been synchronized to GitHub Open source project : Java The road of supernatural more Java Related knowledge , Welcome to visit !
边栏推荐
- Why should I change my PC to a cloud desktop server? What are the characteristics of this server?
- What are the functions of Fortress machine equipment
- RI Geng series: tricks of using function pointers
- On Sunday, I rolled up the uni app "uview excellent UI framework"
- Tens of millions of Android infected with malicious virus and Microsoft disabled a function of Excel | global network security hotspot on October 9
- Differences between EDI and VMI
- Grpc: how to implement distributed log tracing?
- Go program lifecycle
- [summary of interview questions] zj5
- Technical dry goods - how to use AI technology to accurately identify mining Trojans
猜你喜欢
![[summary of interview questions] zj6 redis](/img/4b/eadf66ca8d834f049f3546d348fa32.jpg)
[summary of interview questions] zj6 redis

Ar 3D map technology

Get to know MySQL database

QT creator tips

Simple and beautiful weather code

Sorting out of key vulnerabilities identified by CMS in the peripheral management of red team (I)

On Sunday, I rolled up the uni app "uview excellent UI framework"

Community pycharm installation visual database
![[summary of interview questions] zj5](/img/d8/ece82f8b2479adb948ba706f6f5039.jpg)
[summary of interview questions] zj5
随机推荐
How do I check the trademark registration number? Where do I need to check?
Concise and practical time code
What is the difference between server leasing and hosting?
What are the configuration requirements for cloud desktop servers? What are the main characteristics of the three points?
Why do I need a code signing certificate? Where can I get a code signing certificate?
Why should I change my PC to a cloud desktop server? What are the characteristics of this server?
Ligature in font design
How to select a server with appropriate configuration when planning to build a live broadcast platform
Liaoyuan social cloud primary actual combat camp test environment script
Three Scheduling Strategies in yarn
What is the principle of intelligent image recognition? What are the applications of intelligent image recognition?
How much is a fortress machine? Why do you need a fortress machine?
Elk7.15.1 installation, deployment and construction
[hot] with a budget of only 100 yuan, how to build a 1-year web site on Tencent cloud??
Under what circumstances do you need a fortress machine? What are the functions of a fortress machine
If the cloud knows that security is important
Grand summary of boutique idea plug-ins! Worth collecting
What does elastic public IP mean? The advantages of elastic public IP
How to apply for trademark registration? What are the steps?
Actual combat | how to use micro build low code to realize tolerance application