Home > Database > Mysql Tutorial > body text

How to create MySQL stored procedures and functions

王林
Release: 2023-06-03 09:22:42
forward
1832 people have browsed it

1.0 Create stored procedures and functions

Creating stored procedures and functions is to combine a set of frequently used SQL statements together and store these SQL statements as a whole in the MySQL server

1. Create a stored procedure

CREATE PROCEDURE procedure_name ([proc_param[,...]])
    [characteristic ...] routine_body
Copy after login
  • procedure_name represents the name of the stored procedure to be created

  • proc_param represents the parameters of the stored procedure

  • characteristic represents the characteristics of the stored procedure

  • routine_body represents the SQL statement of the stored procedure

procedure_name cannot be repeated The syntax form of each parameter in name

proc_param is as follows. Each parameter consists of three parts, namely input/output type, parameter name and parameter type. There are three input and output types, namely IN, OUT, and INOUT. param_name represents the parameter name, type represents the parameter type

[ IN | OUT | INOUT ] param_name type
Copy after login

characteristic specifies the characteristics of the stored procedure, and has the following values:

  • LANGUAGE SQL: indicates that the stored procedure is used Written in SQL language

  • [NOT] DETERMINISTIC: Indicates whether the result of the stored procedure execution is correct. DETERMINISTIC indicates that the result is certain, that is, every time the stored procedure is executed, the same input will get the same result. The output; NOT DETERMINISTIC means that the result is uncertain. The same input may get different outputs. The default is NOT DETERMINISTIC

  • {CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA}: Indicates the restrictions on the use of SQL statements by the subprogram. CONTAINS SQL indicates that the subprogram does not contain statements for reading or writing data. NO SQL indicates that the subprogram does not contain SQL. READS SQL DATA indicates that the subprogram contains statements for reading data, but does not include Statements for writing data, MODIFIES SQL DATA means that the subroutine contains statements for writing data

  • SQL SECURITY {DEFINER | INVOKER}: Indicates who has the permission to execute, DEFINER means that only the definer can execute, INVOKER means that the caller with permission can execute, the default is DEFINER

  • COMMENT 'string': comment information, which can be used to describe the stored procedure or function

Example: Create a stored procedure to query the salaries of all employees in the table t_employee

DELIMITER $$
CREATE PROCEDURE proc_employee()
COMMENT '查询员工薪水'
BEGIN
	SELECT salary FROM t_employee
END;
$$
DELIMITER ;
Copy after login

The default in MySQL is semicolon; as the statement terminator, and the SQL statement in the stored procedure needs to be terminated by a semicolon , in order to avoid conflicts, first use DELIMITER $$ to set the end character of MySQL to $$, and then use DELIMITER ; to restore the end character to a semicolon

2. Create a stored function

CREATE FUNCTION fun_name([func_param,[,...]])
	[characteristic ...] routine_body
Copy after login
  • fun_name represents the function name

  • func_param represents the parameter of the function

  • characteristic represents the function characteristics, the value is the same as that of the stored procedure The values ​​are the same

  • routine_body represents the SQL statement of the function

The syntax of each parameter in func_param is as follows, which are parameter name and parameter type

param_type type

Still the previous example

DELIMITER $$
	CREATE FUNCTION func_employee(id INT(4))
		RETURNS INT(6)
	COMMENT '查询员工薪水'
	BEGIN
		SELECT salary FROM t_employee
	END;
	$$
DELIMITER ;
Copy after login

2|0 variable

In MySQL, you can define and use variables, these The scope of variables is in the BEGIN ... END program section

1. Define variables

DECLARE var_name[,...] type [DEFAULT value]
Copy after login
  • The keyword DECLARE is used to declare variables

  • The parameter var_name is the name of the variable, multiple variables can be defined at the same time

  • The parameter type is used to specify the type of the variable

  • The DEFAULT value clause sets the default value of the variable to value. When the DEFAULT clause is not used, the default value is NULL

Example: Define the variable sql_test, the data type is INT, and the default value is 10

DECLARE test_sql INT DEFAULT 10;
Copy after login

2. Variable assignment

SET var_name=expr[,var_name=expr]...
Copy after login
  • The keyword SET is used to assign values ​​to variables

  • The parameter var_name is a variable The name

  • The parameter expr is an assignment expression

Example: Assign the variable sql_test to 30

SET test_sql = 30;
Copy after login

3|0 definition Conditions and handlers

Defining conditions and handlers is to define in advance the problems that may be encountered during program execution, and the ability to solve these problems can be defined in the handler

1. Define conditions

DECLARE condition_name CONDITION FOR condition_value
condition_value:
SQLSTATE[VALUE] sqlstate_value|mysql_error_code
Copy after login
  • The parameter condition_name represents the condition name

  • The parameter condition_value represents the condition type

  • The parameter sqlstate_value and The parameter mysql_error_code can represent MySQL errors

Example: Define ERROR 1146 (42S02) error, named can_not_find, which can be defined in two different ways

// 方法一:使用sqlstate_value
DECLARE can_not_find CONDITION FOR SQLSTATE '42S02';
// 方法二:使用mysql_error_code
DECLARE can_not_find CONDITION FOR 1146;
Copy after login

2. Define the handler

DECLARE handler_type HANDLER FOR condition_value[,...] proc_statement
handler_type:
CONTINUE|EXIT|UNDO
condition_value:
SQLSTATE[VALUE]sqlstate_value|condition_name|SQLWARNING|NOT FOUND|SQLEXCEPTION|mysql_error_code
Copy after login
  • handler_type indicates the error handling method: this parameter has three values:

    • CONTINUE: means If an error is encountered, it will not be processed and the execution will continue.

    • EXIT: Indicates exiting immediately upon encountering an error

    • UNDO: Indicates withdrawing after encountering an error Previous operation

  • condition_value represents the error type, which can have the following values:

    • SQLSTATE[VALUE]sqlstate_value contains A 5-character string error value

    • condition_name represents the error condition name defined by DECLARE CONDITION

    • SQLWARNING 匹配所有 01 开头的 SQLSTATE 错误代码

    • NOT FOUND 匹配所有 02 开头的 SQLSTATE 错误代码

    • SQLEXCEPTION 匹配所有没有被 SQLWARNING 或 NOT FOUND 捕获的 SQLSTATE 错误代码

    • mysql_error_code 匹配数值类型错误代码

  • proc_statement 匹配数值类型错误代码

下面是定义处理程序的几种示例方式:

// 方法一:捕获sqlstate_value
DECLARE CONTINUE HANDLER FOR SQLSTATE '42S02'
SET @info='NOT FOUND';
// 方法二:使用mysql_error_code 
DECLARE CONTINUE HANDLER FOR 1146
SET @info='NOT FOUND';
// 方法三:先定义条件,然后调用
ECLARE can_not_find CONDITION FOR 1146;
DECLARE CONTINUE HANDLER FOR can_not_find
SET @info='NOT FOUND';
// 方法四:使用SQLWARNING
DECLARE EXIT HANDLER FOR SQLWARNING 
SET @info='ERROR';
// 方法五:使用NOT FOUND
DECLARE EXIT HANDLER FOR NOT FOUND
SET @info='NOT FOUND';
// 方法六:使用SQLEXCEPTION 
DECLARE EXIT HANDLER FOR 使用SQLEXCEPTION
SET @info='ERROR';
Copy after login

4|0光标

在存储过程和函数中,可以使用光标逐条读取查询结果集中可能出现的多条记录。光标必须声明在处理程序之前,声明在变量和条件之后

1. 声明光标

DECLARE cursor_name CURSOR
FOR select_statement;
Copy after login
  • 参数 cursor_name 表示光标名称

  • 参数 select_statement 表示 SELECT 语句

下面声明一个名为 cur_employee 的光标

DECLARE cur_employee CURSOR
FOR SELECT name,age FROM t_employee;
Copy after login

2. 打开光标

OPEN cursor_name;
Copy after login
  • 参数 cursor_name 表示光标的名称

下面打开一个名为 cur_employee 的光标

OPEN cur_employee;
Copy after login

3. 使用光标

FETCH cursor_name
INTO var_name[,var_name...]
Copy after login
  • cursor_name 表示光标的名称

  • var_name 表示将光标中的 SELECT 语句查询出来的信息存入该参数,该参数必须在声明光标之前就定义好

下面打开一个名为 cur_employee 的光标,将查询的数据存入 emp_name 和 emp_age 这两个变量中

FETCH cur_employee INTO emp_name,emp_age;
Copy after login

4. 关闭光标

CLOSE cursor_name
Copy after login
  • cursor_name 表示光标的名称

5|0流程控制

1. IF 语句

IF search_condition THEN statement_list
 [ELSEIF search_condition THEN statement_list]...
 [ELSE statement_list]
END IF
Copy after login
  • 参数 search_condition 表示条件判断语句

  • 参数 statement_list 表示不同条件的执行语句

下面是一个 IF 语句的示例

IF age>20 THEN SET @count1=@conut1+1;
	ELSEIF age=20 THEN @count2=@conut2+1;
	ELSE @count3=@count3+1;
END IF;
Copy after login

2. CASE 语句

CASE case_value
	WHEN when_value THEN statement_list
	[WHEN when_value THEN statement_list]...
	[ELSE statement_list]
END CASE
Copy after login
  • 参数 case_value 表示条件判断的变量

  • 参数 when_value 表示变量的取值

  • 参数 statement_list 表示不同 when_value 的执行语句

下面的是一个 CASE 语句的示例

CASE age
	WHEN 20 THEN SET @count1=@count1+1;
	ELSE SET @count2=@count2+1;
END CASE;
Copy after login

3. LOOP 语句

[begin_label:]LOOP
	statement_list
END LOOP [end_label]
Copy after login
  • 参数 begin_label 和参数 end_label 分别表示循环开始和结束的标志,必须相同,而且都可以省略

  • 参数 statement_list 表示需要循环执行的语句

下面是一个 LOOP 语句的示例

add_num:LOOP
	SELECT @count1=@count1+1;
END LOOP add_num
Copy after login

4. LEAVE 语句

主要用于跳出循环

LEAVE label
Copy after login
  • 参数 label 表示循环的标志

下面是一个 LEAVE 语句的示例

add_num:LOOP
	SELECT @count1=@count1+1;
	IF @count1=100 THEN
		LEAVE add_num;
END LOOP add_num
Copy after login

5. ITERATE 语句

也是用于跳出循环,不过是跳出本次循环,直接进入下次循环,类似 Java 的 continue

ITERATE label
Copy after login

ITERATE label

  • 参数 label 表示循环的标志

下面是一个 ITERATE 语句的示例

add_num:LOOP
	SELECT @count1=@count1+1;
	IF @count1=100 THEN
		LEAVE add_num;
	ELSE IF MOD(@count1,3)=0 THEN
		ITERATE add_num;
	SELECT * FROM employee;
END LOOP add_num
Copy after login

6. REPEAT 语句

REPEAT 语句是由条件的控制循环语句,当满足特定条件就会退出循环语句

[begin_label:]REPEAT
	statement_list
	UNTIL search_condition
END REPEAT [end_label]
Copy after login
  • 参数 statement_list 表示需要循环执行的语句

  • 参数 search_condition 表示结束循环的条件,满足该条件即结束循环

下面是一个 REPEAT 语句的示例

add_num:REPEAT
	SELECT @count1=@count1+1;
	UNTIL @count1=100
END REPEAT add_num
Copy after login

7. WHILE 语句

WHILE 语句也是有条件控制的循环语句,与 REPEAT 语句不同的是,WHILE 语句是当满足条件时执行循环内的语句

[begin_label:]WHILE search_condition DO
	statement_list
END WHILE [end_label]
Copy after login
  • 参数 statement_list 表示需要循环执行的语句

  • 参数 search_condition 表示结束循环的条件,满足该条件即结束循环

下面是一个 WHILE 语句的示例

WHILE @count<100 DO
	SET @count=@count+1;
END WHILE;
Copy after login

6|0操作存储过程和函数

1. 调用存储过程

在 MySQL 中,使用 CALL 语句来调用存储过程

CALL proc_name([parameter[,...]])
Copy after login
  • proc_name 是存储过程的名称

  • paramter 是指存储过程的参数

2. 调用存储函数

在 MySQL 中,存储函数的使用方法和 MySQL 内部函数是一样的

3. 使用 SHOW STATUS 语句查看存储过程和函数的状态

SHOW {PROCEDURE|FUNCTION} STATUS{LIKE &#39;pattern&#39;}
Copy after login
  • 参数 PROCEDURE 表示查询存储过程,FUNCTION 表示存储函数

  • 参数 LIKE 'pattern' 用来匹配存储过程或函数的名称

4. 使用 SHOW CREATE 语句查看存储过程和函数的定义

SHOW CREATE {PROCEDURE|FUNCTION} proc_name
Copy after login

5. 从 information_schema.Routine 表中查看存储过程和函数的信息

SELECT * FROM information_schema.Routine
WHERE ROUTINE_NAME=&#39;proc_name&#39;
Copy after login

6. 修改存储过程和函数

ALTER {PROCEDURE|FUNCTION} proc_name[characteristic...];
characteristic:
	{CONTAINS SQL|NO SQL|READS SQL DATA|MODIFIES SQL DATA}
|SQL SECURITY{DEFINER|INVOKER}
|COMMENT &#39;string&#39;
Copy after login
  • 参数 proc_name 表示存储过程或函数的名称

  • 参数 characteristic 指定存储过程的特性:

    • CONTAINS SQL 表示子程序包含 SQL 语句,但不包含读或写数据的语句

    • NO SQL 表示子程序不包含 SQL 语句

    • READS SQL DATA 表示子程序中包含读数据的语句

    • MODIFIES SQL DATA 表示子程序中包含写数据的语句

  • SQL SECURITY{DEFINER|INVOKER} 指明谁有权限执行:

    • DEFINER 表示只有定义者才能执行

    • INVOKER 表示调用者可以执行

  • COMMENT 'string' 是注释信息

7. 删除存储过程和函数

通过 DROP 语句删除存储过程

DROP PROCEDURE proc_name;
Copy after login

通过 DROP FUNCTION 语句删除存储函数

DROP FUNCTION func_name;
Copy after login

The above is the detailed content of How to create MySQL stored procedures and functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template