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

  1. 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();
 ```
  1. 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

  1. IF( expression 1, expression 2, expression 3) If the expression 1 establish , return 2, Otherwise return to 3
  2. 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 !

原网站

版权声明
本文为[Kaiyuanjun]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/10/20211003163811110k.html