当前位置:网站首页>Stored procedures and functions (MySQL)
Stored procedures and functions (MySQL)
2022-07-07 03:16:00 【JiaXingNashishua】
Catalog
One : Overview of stored procedures
3、 ... and : Calling stored procedure
4.2 Calling the storage function
4.4 Compare stored functions with stored procedures
5、 ... and . View of stored procedures and functions 、 modify 、 Delete
One : Overview of stored procedures
1.1 understand :
meaning :
The English of stored procedure is Stored Procedure . Its idea is very simple , It's just a group of people passing through Precompile Of SQL Encapsulation of statements .
Execution process :
Stored procedures are pre stored in MySQL Server , When it needs to be implemented , The client only needs to issue a command to the server to call the stored procedure , The server side can store the pre stored series SQL Execute all statements .
And views 、 Comparison of functions :
It has the same advantages as view , Clear 、 Security , It can also reduce the amount of network transmission . But it's different from the view , View is Virtual table , Usually do not directly operate on the underlying data table , and Stored procedures are programmed SQL, Sure Directly operate the underlying data table , Compared with the collection oriented operation , It can realize some more complex data processing .
Once the stored procedure is created , Using it is as simple as using a function , We can just call the stored procedure name directly . Compared to the function , The stored procedure is no return value Of .
1.2 classification :
The parameter type of the stored procedure can be IN、OUT and INOUT. According to this classification is as follows :
- 1、 No parameters ( No parameters, no return )
- 2、 Just bring IN type ( No return with parameters )
- 3、 Just bring OUT type ( No parameters return )
- 4、 With both IN And bring OUT( There are parameters and returns )
- 5、 belt INOUT( There are parameters and returns )
Be careful :IN、OUT、INOUT You can take more than one in one stored procedure .
Two : Create stored procedure
2.1 Syntax analysis :
grammar :
CREATE PROCEDURE Stored procedure name (IN|OUT|INOUT Parameter name Parameter type ,...)
[characteristics ...]
BEGIN
Stored procedure body
END
Be similar to Java The method in :
Modifier Return type Method name ( Parameter type Parameter name ,...){
Method body ;
}
explain :
1、 The meaning of the symbol before the parameter
- IN : The current parameter is the input parameter , That is to say, the input parameter ; The stored procedure just reads the value of this parameter . If no parameter type is defined , The default is IN , Represents input parameter .
- OUT : The current parameter is the output parameter , That is to say, it shows that ; After the execution is complete , The client or application calling the stored procedure can read the value returned by the parameter .
- INOUT : The current parameter can be either an input parameter , It can also be an output parameter .
2、 The formal parameter type can be MySQL Any type in the database .
3、 characteristics Represents the constraint on the stored procedure specified when creating the stored procedure , The value information is as follows :
LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'
- LANGUAGE SQL : Note that the stored procedure execution body is composed of SQL The sentences make up , The languages supported by the current system are SQL.
- [NOT] DETERMINISTIC : Indicates whether the result of the stored procedure execution is determined .DETERMINISTIC Indicates that the result is certain . Every time a stored procedure is executed , The same input gets the same output .NOT DETERMINISTIC Indicates that the result is uncertain , The same input may get different outputs . If no value is specified , The default is NOTDETERMINISTIC.
- { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } : Indicates that the subroutine uses SQL Sentence restrictions .
- SQL SECURITY { DEFINER | INVOKER } : Permission to execute the current stored procedure , That is, indicate which users can execute
Row current stored procedure . - COMMENT 'string' : Annotation information , Can be used to describe stored procedures .
- CONTAINS SQL Indicates that the subroutine of the current stored procedure contains SQL sentence , But it doesn't contain read-write data SQL sentence ;
- NO SQL Indicates that the subroutine of the current stored procedure does not contain any SQL sentence ;
- READS SQL DATA Indicates that the subroutine of the current stored procedure contains read data SQL sentence ;
- MODIFIES SQL DATA Indicates that the subroutine of the current stored procedure contains data to be written SQL sentence .
- By default , The system specifies as CONTAINS SQL.
DEFINER Indicates that only the creator or definer of the current stored procedure can execute the current stored procedure ;
INVOKER Indicates that a user with access to the current stored procedure can execute the current stored procedure .
If the relevant value is not set , be MySQL The default specified value is DEFINER.
4、 There can be more than one in the stored procedure body SQL sentence , If only one SQL sentence , You can omit BEGIN and END
Writing stored procedures is not a simple thing , It is possible that the stored procedure requires complex SQL sentence .
1. BEGIN…END:BEGIN…END There are multiple statements in the middle , Each statement starts with (;) The sign is the Terminator .
2. DECLARE:DECLARE Used to declare variables , The position of use is BEGIN…END In the middle of the sentence , And it needs to be used before other statements
Declaration of line variables .
3. SET: Assignment statement , Used to assign values to variables .
4. SELECT… INTO: Store the query results from the data table into variables , That is, assign values to variables .
5、 You need to set a new end tag
DELIMITER: End of new tag
- because MySQL The default statement end symbol is semicolon ‘;’. To avoid problems with stored procedures SQL Statement terminator conflicts , Need to use DELIMITER Changes the end of a stored procedure .
- such as :“DELIMITER //” The statement will MySQL Is set to //, And “END //” End stored procedure . After the stored procedure is defined, you can use “DELIMITER ;” Restore the default Terminator .DELIMITER You can also specify other symbols as endings .
- When using DELIMITER On command , Backslashes should be avoided (‘\’) character , Because the backslash is MySQL The escape character of .
2.2 The code for :
give an example 1: Create stored procedure select_all_data(), see emps All data of table
DELIMITER $
CREATE PROCEDURE select_all_data()
BEGIN
SELECT * FROM emps;
END $
DELIMITER ;
give an example 2: Create stored procedure avg_employee_salary(), Return the average salary of all employees
DELIMITER //
CREATE PROCEDURE avg_employee_salary ()
BEGIN
SELECT AVG(salary) AS avg_salary FROM emps;
END //
DELIMITER ;
give an example 3: Create stored procedure show_max_salary(), To view “emps” The highest salary value in the table .
CREATE PROCEDURE show_max_salary()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ' View maximum salary '
BEGIN
SELECT MAX(salary) FROM emps;
END //
DELIMITER ;
give an example 4: Create stored procedure show_min_salary(), see “emps” The minimum salary value of the table . And pass the minimum wage OUT Parameters “ms” Output
DELIMITER //
CREATE PROCEDURE show_min_salary(OUT ms DOUBLE)
BEGIN
SELECT MIN(salary) INTO ms FROM emps;
END //
DELIMITER ;
give an example 5: Create stored procedure show_someone_salary(), see “emps” The salary of an employee in the table , And use IN Parameters empname Enter employee name .
DELIMITER //
CREATE PROCEDURE show_someone_salary(IN empname VARCHAR(20))
BEGIN
SELECT salary FROM emps WHERE ename = empname;
END //
DELIMITER ;
give an example 6: Create stored procedure show_someone_salary2(), see “emps” The salary of an employee in the table , And use IN Parameters empname Enter employee name , use OUT Parameters empsalary Output employee salary .
DELIMITER //
CREATE PROCEDURE show_someone_salary2(IN empname VARCHAR(20),OUT empsalary DOUBLE)
BEGIN
SELECT salary INTO empsalary FROM emps WHERE ename = empname;
END //
DELIMITER ;
give an example 7: Create stored procedure show_mgr_name(), Query the name of an employee leader , And use INOUT Parameters “empname” Enter employee name , Output the name of the leader .
DELIMITER //
CREATE PROCEDURE show_mgr_name(INOUT empname VARCHAR(20))
BEGIN
SELECT ename INTO empname FROM emps
WHERE eid = (SELECT MID FROM emps WHERE ename=empname);
END //
DELIMITER ;
3、 ... and : Calling stored procedure
Stored procedures have a variety of calling methods . Stored procedures must use CALL The statement calls , And the stored procedure is related to the database , If you want to execute stored procedures in other databases , You need to specify a database name , for example CALL dbname.procname.
CALL Stored procedure name ( Argument list )
Format :
1、 call in Parameters of the pattern :
CALL sp1(' value ');
2、 call out Parameters of the pattern :
SET @name;
CALL sp1(@name);
SELECT @name;
3、 call inout Parameters of the pattern :
SET @name= value ;
CALL sp1(@name);
SELECT @name;
3.2 The code for
give an example 1:
DELIMITER //
CREATE PROCEDURE CountProc(IN sid INT,OUT num INT)
BEGIN
SELECT COUNT(*) INTO num FROM fruits
WHERE s_id = sid;
END //
DELIMITER ;
Calling stored procedure :
mysql> CALL CountProc (101, @num);
Query OK, 1 row affected (0.00 sec)
View return results :
mysql> SELECT @num;
The stored procedure returns the specified s_id=101 The types of fruit offered by our fruit merchants , The return value is stored in num variable , Use SELECT see , The return result is 3.
3.3 How to debug
stay MySQL in , Stored procedures are not like ordinary programming languages ( such as VC++、Java etc. ) There is a special integrated development environment . therefore , You can go through SELECT sentence , Query the intermediate results of program execution , To debug a SQL Statement correctness . After successful debugging , hold SELECT Move to the next... After the statement SQL After statement , Debug the next SQL sentence . such Step by step , You can complete the debugging of all operations in the stored procedure . Of course , You can also put... In a stored procedure SQL Copy the statement , Separate commissioning section by section .
Four : Storage function
I learned a lot of functions earlier , Using these functions, you can perform various processing operations on data , Greatly improve the user's management efficiency of the database .MySQL Support for custom functions , Once defined , The calling method is the same as the calling method MySQL Like predefined system functions .
4.1 Syntax analysis
The functions I've learned :LENGTH、SUBSTR、CONCAT etc.
Grammar format :
CREATE FUNCTION Function name ( Parameter name Parameter type ,...)
RETURNS return type
[characteristics ...]
BEGIN
The body of the function # There must be... In the body of the function RETURN sentence
END
explain :
1、 parameter list : The specified parameter is IN、OUT or INOUT Only right PROCEDURE It's legal. ,FUNCTION It always defaults to IN Parameters .
2、RETURNS type Statement represents the type of data returned by the function ;RETURNS Clause can only be used for FUNCTION Make a designation , For functions, this is mandatory Of . It is used to specify the return type of the function , And the body of the function must contain a RETURN value sentence .
3、characteristic The constraint on the function specified when creating the function . The value is the same as when creating the stored procedure , No more details here .
4、 The function body can also be used BEGIN…END To express SQL The beginning and end of the code . If the function body has only one statement , You can omit it BEGIN…END.
4.2 Calling the storage function
stay MySQL in , How to use the storage function is the same as MySQL The use of internal functions is the same . In other words , User defined storage functions and MySQL The internal function is a property . The difference lies in , The storage function is User defined Of , And the inner function is MySQL Of Developer definition Of .
SELECT Function name ( Argument list )
4.3 The code for
give an example 1:
Create a storage function , The name is email_by_name(), Parameter definition is null , This function queries Abel Of email, And back to , The data type is string .
DELIMITER //
CREATE FUNCTION email_by_name()
RETURNS VARCHAR(25)
DETERMINISTIC
CONTAINS SQL
BEGIN
RETURN (SELECT email FROM employees WHERE last_name = 'Abel');
END //
DELIMITER ;
call :
SELECT email_by_name();
give an example 2:
Create a storage function , The name is email_by_id(), Parameters of the incoming emp_id, This function queries emp_id Of email, And back to , The data type is string .
DELIMITER //
CREATE FUNCTION email_by_id(emp_id INT)
RETURNS VARCHAR(25)
DETERMINISTIC
CONTAINS SQL
BEGIN
RETURN (SELECT email FROM employees WHERE employee_id = emp_id);
END //
DELIMITER ;
call :
SET @emp_id = 102;
SELECT email_by_id(102);
give an example 3:
Create a storage function count_by_id(), Parameters of the incoming dept_id, This function queries dept_id Number of employees in the Department , And back to , The data type is integer .
DELIMITER //
CREATE FUNCTION count_by_id(dept_id INT)
RETURNS INT
LANGUAGE SQL
NOT DETERMINISTIC
READS SQL DATA
SQL SECURITY DEFINER
COMMENT ' Query the average salary of the Department '
BEGIN
RETURN (SELECT COUNT(*) FROM employees WHERE department_id = dept_id);
END //
DELIMITER ;
call :
SET @dept_id = 50;
SELECT count_by_id(@dept_id);
Be careful :
If an error is reported in creating a storage function “ you might want to use the less safe
log_bin_trust_function_creators variable ”, There are two ways to deal with it :
The way 1: Add the necessary functional features “[NOT] DETERMINISTIC” and “{CONTAINS SQL | NO SQL | READS SQL DATA |MODIFIES SQL DATA}”The way 2:mysql> SET GLOBAL log_bin_trust_function_creators = 1;( Run this statement before creating the storage function )
4.4 Compare stored functions with stored procedures
Besides , Storage functions can be used in query statements , Stored procedures don't work . conversely , Stored procedures are more powerful , Including the ability to perform operations on tables ( For example, create a table , Delete tables, etc ) And transaction operations , These functions are not available in storage functions .
5、 ... and . View of stored procedures and functions 、 modify 、 Delete
5.1 see
After creation , How do we know the stored procedure we created 、 Is the storage function successful ?
MySQL It stores the state information of stored procedures and functions , Users can use SHOW STATUS Sentence or SHOW CREATE Statement to see , It can also be directly from the... Of the system information_schema Query in database . Here are 3 Methods .
1. Use SHOW CREATE Statement to view the creation information of stored procedures and functions
The basic grammatical structure is as follows :
SHOW CREATE {PROCEDURE | FUNCTION} Stored procedure name or function name
give an example :
SHOW CREATE FUNCTION test_db.CountProc \G
2. Use SHOW STATUS Statement to view the status information of stored procedures and functions
The basic grammatical structure is as follows :
SHOW {PROCEDURE | FUNCTION} STATUS [LIKE 'pattern']
This statement returns the characteristics of the subroutine , Such as a database 、 name 、 type 、 Creator and date of creation and modification .
[LIKE 'pattern']: Matches the name of a stored procedure or function , It can be omitted . When omitted without writing , Will list MySQL Information about all stored procedures or functions that exist in the database . give an example :SHOW STATUS Statement example , The code is as follows :
mysql> SHOW PROCEDURE STATUS LIKE 'SELECT%' \G
*************************** 1. row ***************************
Db: test_db
Name: SelectAllData
Type: PROCEDURE
Definer: [email protected]
Modified: 2021-10-16 15:55:07
Created: 2021-10-16 15:55:07
Security_type: DEFINER
Comment:
character_set_client: utf8mb4
collation_connection: utf8mb4_general_ci
Database Collation: utf8mb4_general_ci
1 row in set (0.00 sec)
3. from information_schema.Routines View the information of stored procedures and functions in the table
MySQL The information of stored procedures and functions is stored in information_schema Database based Routines In the table . You can query the information of stored procedures and functions by querying the records of the table . Its basic grammatical form is as follows :
SELECT * FROM information_schema.Routines
WHERE ROUTINE_NAME=' The name of a stored procedure or function ' [AND ROUTINE_TYPE = {'PROCEDURE|FUNCTION'}];
explain : If in MySQL The stored procedure and function names are the same in the database , It's better to designate ROUTINE_TYPE Query criteria to indicate whether the query is a stored procedure or a function .
give an example : from Routines The query name in the table is CountProc Information about the storage function of , The code is as follows :
SELECT * FROM information_schema.Routines
WHERE ROUTINE_NAME='count_by_id' AND ROUTINE_TYPE = 'FUNCTION' \G
5.2 modify
Modify stored procedures or functions , Does not affect stored procedure or function functions , Just modify the relevant features . Use ALTER Statements for .
ALTER {PROCEDURE | FUNCTION} The name of a stored procedure or function [characteristic ...]
among ,characteristic Specify the properties of the stored procedure or function , Its value information is the same as that of creating a stored procedure 、 The value information of function is slightly different .
{ CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'
- CONTAINS SQL , Indicates that the subroutine contains SQL sentence , But does not contain statements that read or write data .
- NO SQL , Indicates that the subroutine does not contain SQL sentence .
- READS SQL DATA , A statement that contains read data in a subroutine .
- MODIFIES SQL DATA , Represents a statement in a subroutine that contains data to be written .
- SQL SECURITY { DEFINER | INVOKER } , Indicate who has authority to execute . among ,DEFINER , It means that only the definer himself can execute .INVOKER , Indicates that the caller can execute .
- COMMENT 'string' , Represents annotation information .
Modify stored procedures to use ALTER PROCEDURE sentence , Modify the storage function to use ALTER FUNCTION sentence . however , The structure of these two statements is the same , All parameters in the statement are the same .
give an example 1:
Modify stored procedure CountProc The definition of . Change the read and write permissions to MODIFIES SQL DATA, And indicate that the caller can execute , The code is as follows :
ALTER PROCEDURE CountProc
MODIFIES SQL DATA
SQL SECURITY INVOKER ;
Query the modified information :
SELECT specific_name,sql_data_access,security_type
FROM information_schema.`ROUTINES`
WHERE routine_name = 'CountProc' AND routine_type = 'PROCEDURE';
Results show , The stored procedure was modified successfully . From the results of the query, we can see , Access to data (SQL_DATA_ ACCESS) Has become a MODIFIES SQL DATA, Security type (SECURITY_TYPE) Has become a INVOKER.
give an example 2:
Modify storage function CountProc The definition of . Change the read and write permissions to READS SQL DATA, And add the comment information “FIND NAME”, The code is as follows :
ALTER FUNCTION CountProc
READS SQL DATA
COMMENT 'FIND NAME' ;
Storage function modified successfully . From the results of the query, we can see , Access to data (SQL_DATA_ACCESS) Has become a READSSQL DATA, Function Comments (ROUTINE_COMMENT) Has become a FIND NAME.
5.3 Delete
Deletes stored procedures and functions , have access to DROP sentence , The syntax is as follows :
DROP {PROCEDURE | FUNCTION} [IF EXISTS] The name of a stored procedure or function
IF EXISTS: If a program or function does not store , It can prevent errors , Make a use of SHOW WARNINGS View warnings for .
give an example :
DROP PROCEDURE CountProc;
DROP FUNCTION CountProc;
边栏推荐
- mos管實現主副電源自動切換電路,並且“零”壓降,靜態電流20uA
- leetcode
- Simple bubble sort
- 【基于 RT-Thread Studio的CPK-RA6M4 开发板环境搭建】
- The first symposium on "quantum computing + application of financial technology" was successfully held in Beijing
- Centerx: open centernet in the way of socialism with Chinese characteristics
- 知识图谱构建全流程
- How to verify accesstoken in oauth2 protocol
- How to find file accessed / created just feed minutes ago
- Shell programming basics
猜你喜欢
How to verify accesstoken in oauth2 protocol
Le tube MOS réalise le circuit de commutation automatique de l'alimentation principale et de l'alimentation auxiliaire, et la chute de tension "zéro", courant statique 20ua
Es6中Promise的使用
Centerx: open centernet in the way of socialism with Chinese characteristics
知识图谱构建全流程
uniapp的表单验证
A complete tutorial for getting started with redis: problem location and optimization
密码学系列之:在线证书状态协议OCSP详解
Starting from 1.5, build a micro Service Framework -- log tracking traceid
When you go to the toilet, you can clearly explain the three Scheduling Strategies of scheduled tasks
随机推荐
C language string sorting
商城商品的知识图谱构建
How-PIL-to-Tensor
An error in SQL tuning advisor ora-00600: internal error code, arguments: [kesqsmakebindvalue:obj]
硬件之OC、OD、推挽解释
如何分析粉丝兴趣?
Jerry's FM mode mono or stereo selection setting [chapter]
腾讯云原生数据库TDSQL-C入选信通院《云原生产品目录》
OC, OD, push-pull explanation of hardware
Jerry's phonebook acquisition [chapter]
HDU 4337 King Arthur's Knights 它输出一个哈密顿电路
Jerry's transmitter crashed after the receiver shut down [chapter]
Redis getting started complete tutorial: common exceptions on the client
c语言(字符串)如何把字符串中某个指定的字符删除?
Lost in the lock world of MySQL
房费制——登录优化
opencv环境的搭建,并打开一个本地PC摄像头。
[socket] ① overview of socket technology
【Swift】学习笔记(一)——熟知 基础数据类型,编码风格,元组,主张
IDEA重启后无法创建Servlet文件的解决方案