当前位置:网站首页>The concepts and differences between MySQL stored procedures and stored functions, as well as how to create them, the role of delimiter, the viewing, modification, deletion of stored procedures and fu
The concepts and differences between MySQL stored procedures and stored functions, as well as how to create them, the role of delimiter, the viewing, modification, deletion of stored procedures and fu
2022-07-02 01:46:00 【No development, no work】
List of articles
1 summary
1.1 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 .
1.2 Storage function
MySQL Support for custom functions , Once defined , The calling method is the same as the calling method MySQL Like predefined system functions .
2 establish
2.1 Create stored procedure
2.1.1 grammar
CREATE PROCEDURE Stored procedure name (IN | OUT | INOUT Parameter name Parameter type ,...)
[characteristics ...]
BEGIN
Stored procedure body
END
2.1.2 Parameter list
- No parameters ( No parameters, no return )
- Just bring IN type ( No return with parameters )
- Just bring OUT type ( No parameters return )
- With both IN And bring OUT( There are parameters and returns )
- belt INOUT( There are parameters and returns
Be careful :IN、OUT、INOUT You can take more than one in one stored procedure .
2.1.3 Code
-- Create an empty parameter stored procedure
CREATE PROCEDURE select_all_data ()
BEGIN
SELECT
*
FROM
employees;
END;
-- Calls to stored procedures
CALL select_all_data();
-- Create a OUT stored procedure
CREATE PROCEDURE show_min_salary ( OUT ms DOUBLE ) BEGIN
SELECT
min( salary ) INTO ms
FROM
employees;
END;
-- Calls to stored procedures
-- Define a variable to store the result
CALL show_min_salary(@ms);
-- View variable values
SELECT @ms;
-- Create a IN stored procedure
CREATE PROCEDURE show_someone_salary ( IN emp_name VARCHAR(20) )
BEGIN
SELECT
salary
FROM
employees
WHERE
last_name = emp_name;
END;
-- The calling method of stored procedure I
CALL show_someone_salary('King');
-- The calling method of stored procedure I
SET @emp_name = 'King';
CALL show_someone_salary(@emp_name);
-- Create a IN and OUT Stored procedure
CREATE PROCEDURE show_someone_salary2 ( IN empname VARCHAR ( 20 ), OUT empsalary DOUBLE )
BEGIN
SELECT
salary INTO empsalary
FROM
employees
WHERE
last_name = empname;
END;
-- How to call stored procedures
CALL show_someone_salary2('Kochhar',@empsalary);
SELECT @empsalary;
-- Create a INOUT Stored procedure
CREATE PROCEDURE show_mgr_name (
INOUT empname VARCHAR ( 20 ))
BEGIN
SELECT
last_name INTO
FROM
employees
WHERE
manager_id = ( SELECT employee_id FROM employees WHERE last_name = empname );
END;
-- How to call stored procedures
SET @emp_name = 'De Haan';
CALL show_mgr_name(@emp_name);
SELECT @emp_name;
2.2 Create a storage function
2.2.1 grammar
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;
2.2.2 Code
-- Method 1 of creating null parameter function
CREATE FUNCTION email_by_name()
RETURNS VARCHAR(25)-- Parameter type returned
-- solve you might want to use the less safe log_bin_trust_function_creators variable problem
DETERMINISTIC
CONTAINS SQL
READS SQL DATA
BEGIN
RETURN (SELECT email FROM employees WHERE last_name = 'Abel');
END;
-- Method 2 of creating null parameter function
SET GLOBAL log_bin_trust_function_creators = 1; -- solve you might want to use the less safe log_bin_trust_function_creators variable error
CREATE FUNCTION email_by_name2()
RETURNS VARCHAR(25)
BEGIN
RETURN (SELECT email FROM employees WHERE last_name = 'Abel');
END;
-- Function call
select email_by_name();
-- Create a parametric function
CREATE FUNCTION email_by_id(emp_id INT)
RETURNS VARCHAR(25)
BEGIN
RETURN (SELECT email FROM employees WHERE employee_id = emp_id);
END;
-- Call function
3 delimiter The role of
-- Modify the ending character as &
DELIMITER &
-- Modify the ending character as ;
DELIMITER ;
4 The difference between stored procedure and stored function
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 Error resolution when creating function
error :
you might want to use the less safe log_bin_trust_function_creators variable
solve :
- Mode one : Add the necessary functional features “[NOT] DETERMINISTIC” and “[CONTAINS SQL|NO SQL|READS SQL DATA|MODIFIES SQL DATA}"
- Mode two : SET GLOBAL log_bin_trust_function_creators = 1;
6 View of stored procedures and functions 、 modify 、 Delete
6.1 see
-- 1. Use show create Statement to view the creation information of stored procedures and functions
-- View stored procedures
SHOW CREATE PROCEDURE show_mgr_name;
-- View functions
SHOW CREATE FUNCTION email_by_id;
-- 2. Use show status Statement to view the state information of stored procedures and functions
-- View stored procedures
SHOW PROCEDURE STATUS LIKE 'show_mgr_name';
-- View functions
SHOW FUNCTION STATUS LIKE 'email_by_id';
-- 3. from information_schema.Routines View the information of stored procedures and functions in the table
SELECT * FROM information_schema.Routines WHERE ROUTINE_NAME = ' Stored procedure name or function name ';
-- When duplicate names, specify whether the type is a function or a stored procedure
SELECT * FROM information_schema.Routines WHERE ROUTINE_NAME = 'show_mgr_name' AND ROUTINE_TYPE = 'PROCEDURE';
6.2 modify
ALTER PROCEDURE show_max_salary SQL SECURITY INVOKER COMMENT ' Query maximum wage ';
6.3 Delete
DROP PROCEDURE Stored procedure name ;
DROP FUNCTION Function name ;
7 Advantages and disadvantages of the storage process
7.1 advantage
- Stored procedures can be compiled and used more than once . Stored procedures are compiled only at creation time , There is no need to recompile later , That's a step up SQL Efficiency of execution .
- It can reduce the development workload . Encapsulating code into modules , It's actually one of the core ideas of programming , In this way, complex problems can be broken down into different modules , And then the modules can be reused , While reducing development effort , It also keeps the structure of the code clear .
- The security of stored procedure is strong . When we set the stored procedure, we can set the user's permission , This is as secure as the view .
- It can reduce the amount of network transmission . Because the code is encapsulated in stored procedures , Each time you use it, you just need to call the stored procedure , This reduces the amount of network traffic .
- Good encapsulation . When performing relatively complex database operations , We used to use one by one SQL sentence , Operations that may require multiple database connections to complete , Now it's a stored procedure , Just connect once .
7.2 shortcoming
- Poor portability . Stored procedures cannot be migrated across databases , For example MySQL、Oracle and SQLServer Stored procedures written in , It needs to be rewritten when changing to other databases .
- Debugging difficulty . Only a few DBMS Supports debugging of stored procedures . For complex stored procedures , Development and maintenance are not easy . Although there are some third-party tools that can debug stored procedures , But there's a charge .
- Version management of stored procedures is difficult . For example, the index of the data table has changed , Can cause stored procedures to fail . We often need version management when we develop software , But the stored procedure itself has no version control , It's troublesome to update the version iteratively .
- It is not suitable for high concurrency scenarios . High concurrency scenarios need to reduce the pressure on the database , Sometimes the database will adopt the way of dividing database and table , And it's very scalable , under these circumstances , Stored procedures can become difficult to maintain , Increase the pressure on the database , Obviously not .
边栏推荐
- Memorabilia of domestic database in June 2022
- How to debug apps remotely and online?
- Modeling essays series 124 a simple coding method
- [IVX junior engineer training course 10 papers to get certificates] 03 events and guessing numbers games
- k线图形态这样记(口诀篇)
- 1217 supermarket coin processor
- The author is more willing to regard industrial Internet as a concept much richer than consumer Internet
- Exclusive delivery of secret script move disassembly (the first time)
- Implementation principle of city selector component
- Feature extraction and detection 16 brisk feature detection and matching
猜你喜欢
机器学习基本概念
Game thinking 15: thinking about the whole region and sub region Services
What are the skills of spot gold analysis?
[IVX junior engineer training course 10 papers] 06 database and services
ES6 new method of string
现货黄金分析的技巧有什么呢?
The technology boss is ready, and the topic of position C is up to you
How to use a product to promote "brand thrill"?
How can the tsingsee Qingxi platform play multiple videos at the same time on the same node?
Matlab uses audiorecorder and recordblocking to record sound, play to play sound, and audiobook to save sound
随机推荐
Parted command
遊戲思考15:全區全服和分區分服的思考
微信小程序中使用tabBar
Develop those things: how to use go singleton mode to ensure the security of high concurrency of streaming media?
成功实现边缘编码需要了解的六大经验教训
6-2 vulnerability exploitation - inevitable problems of FTP
matlab 使用 audiorecorder、recordblocking录制声音,play 播放声音,audiowrite 保存声音
Leetcode, 3 repeatless longest subsequence
Learning note 3 -- Key Technologies of high-precision map (Part 1)
No converter found for return value of type: class
Experimental reproduction of variable image compression with a scale hyperprior
How to use a product to promote "brand thrill"?
Four basic strategies for migrating cloud computing workloads
[Maya] the error of importing Maya into Metahuman
5g/4g pole gateway_ Smart pole gateway
Luogu p1775 stone merger (weakened version)
ES6 new method of string
Learn about servlets
Learn C language from scratch day 025 (maze)
Discussion on the idea of platform construction