当前位置:网站首页>15 MySQL stored procedures and functions
15 MySQL stored procedures and functions
2022-07-05 23:41:00 【Old vegetable chicken still needs efforts】
15 MySQL- Stored procedures and functions
MySQL from 5. 0 The version began to support stored procedures and functions . Stored procedures and functions can transform complex SQL Logic encapsulated together , Applications don't have to pay attention to the complex problems inside stored procedures and functions SQL Logic , You just need to simply call stored procedures and functions .
1. Overview of stored procedures
1.1 understand
meaning : save Storage process English 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 .
benefits :
- Simplified operation , Improved sql Statement reusability , Reduce the pressure on developers
- Reduce errors in operation , Increase of efficiency
- Reduce network traffic ( The client does not need to put all SQL The statement is sent to the server through the network ) 4 、 Less SQL The risk of statement exposure to the Internet , It also improves the security of data query
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 :
- 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. 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 :
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 .
The formal parameter type can be MySQL Any type in the database .
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 NOT DETERMINISTIC.{ CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
: Indicates that the subroutine uses SQL Sentence restrictions .
- 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.
SQL SECURITY { DEFINER | INVOKER }
: Permission to execute the current stored procedure , That is, it indicates which users can execute the current stored procedure .
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.
COMMENT 'string'
: Annotation information , Can be used to describe stored procedures .
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 you need to declare variables before other statements are used . 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 .
You need to set a new end tag
DELIMITER New end 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 .
Example :
DELIMITER $ CREATE PROCEDURE Stored procedure name (IN|OUT|INOUT Parameter name Parameter type ,...) [characteristics ...] BEGIN sql sentence 1; sql sentence 2; END $
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. Calling stored procedure
3.1 Invocation format
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 :
call in Parameters of the pattern :
CALL sp1(' value ');
call out Parameters of the pattern :
SET @name; CALL sp1(@name); SELECT @name;
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 .
give an example 2 : Create stored procedure , Realize accumulation operation , Calculation 1+2+…+n How much . The specific code is as follows :
DELIMITER //
CREATE PROCEDURE `add_num`(IN n INT)
BEGIN
DECLARE i INT;
DECLARE sum INT;
SET i = 1 ;
SET sum = 0 ;
WHILE i <= n DO
SET sum = sum + i;
SET i = i + 1 ;
END WHILE;
SELECT sum;
END //
DELIMITER ;
If you're using a Navicat Tools , So when writing stored procedures ,Navicat It's automatically set DELIMITER For other symbols , We don't need to DELIMITER The operation of .
Use it directly CALL add_num(50);
that will do . The parameter I passed in here is 50, That is statistics 1+2+…+50 The sum of accumulation .
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 .
4. Use of 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 :
- parameter list : The specified parameter is IN、OUT or INOUT Only right PROCEDURE It's legal. ,FUNCTION It always defaults to IN Parameters .
- 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 ismandatory
Of . It is used to specify the return type of the function , And the body of the function must contain aRETURN value
sentence . - 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 .
- 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 ;
4.4 Compare stored functions with stored procedures
keyword | Call syntax | Return value | Application scenarios | |
---|---|---|---|---|
stored procedure | PROCEDURE | CALL stored procedure () | Understanding for 0 One or more | Generally used for updating |
Storage function | FUNCTION | SELECT function () | It can only be one | Generally used when the query result is a value and returned |
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. 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]localhost
Modified: 2021 - 10 - 16 15 :55:
Created: 2021 - 10 - 16 15 :55:
Security_type: DEFINER
Comment:
character_set_client: utf8mb
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 .
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 READS SQL 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;
6. Disputes over the use of stored procedures
Although stored procedures have many advantages , But for the use of stored procedures , There has always been a lot of controversy , For example, some companies require the use of stored procedures for large projects , Some companies explicitly prohibit the use of stored procedures in manuals , Why do these companies have such different requirements for stored procedures ?
6.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 . Put the code
encapsulation
Modular , It's actually one of the core ideas of programming , In this way, complex problems can be broken down into different modules , Then the modules canReuse
, While reducing development effort , It also keeps the structure of the code clear . - The security of stored procedure is strong . When setting up stored procedures, we can
Set user permissions
, 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 , It only needs
Connect once
.
6.2 shortcoming
Based on the above advantages , Many large companies require large projects to use stored procedures , Like Microsoft 、IBM Companies such as . But domestic Alibaba does not recommend developers to use stored procedures , Why is that ?
Ali Development Specification
【 mandatory 】 Stored procedures are not allowed , Stored procedures are difficult to debug and extend , There is no portability .
Although stored procedures have advantages like the above , But the disadvantages are obvious .
- Poor portability . Stored procedures cannot be migrated across databases , For example MySQL、Oracle and SQL Server 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 .
Summary :
Stored procedures are convenient , There are limitations . Although different companies have different attitudes towards stored procedures , But for us developers , No matter what , Mastering stored procedures is one of the necessary skills .
7. Exercise
7.1 Exercise1
-- 5. Exercise
-- ---------------------- ---------------------- ----------------------
-- 5.1 Exercise1
# 0. preparation
CREATE DATABASE test15_pro_func;
USE test15_pro_func;
CREATE TABLE admin
(
id INT PRIMARY KEY AUTO_INCREMENT,
user_name VARCHAR(15) NOT NULL,
pwd VARCHAR(25) NOT NULL
);
CREATE TABLE beauty
(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(15) NOT NULL,
phone VARCHAR(15) UNIQUE,
birth DATE
);
INSERT INTO beauty(NAME, phone, birth)
VALUES (' Athena Chu ', '13201233453', '1982-02-12'),
(' Stefanie Sun ', '13501233653', '1980-12-09'),
(' Hebe ', '13651238755', '1983-08-21'),
(' Deng Zi chess ', '17843283452', '1991-11-12'),
(' Liu Ruoying ', '18635575464', '1989-05-18'),
(' Mr Yang, the more ', '13761238755', '1994-05-11');
SELECT *
FROM beauty;
# 1. Create stored procedure insert_user(), Implement the incoming user name and password , Insert into admin In the table
DELIMITER //
CREATE PROCEDURE insert_user(IN uname varchar(15), IN pwd varchar(25))
BEGIN
INSERT INTO admin(user_name, pwd)
VALUES (uname, pwd);
END //
DELIMITER ;
# 2. Create stored procedure get_phone(), Realize the incoming goddess number , Return the goddess name and goddess phone number
DELIMITER //
CREATE PROCEDURE get_phone(IN bid int, OUT bname varchar(15), OUT phone varchar(15))
BEGIN
SELECT NAME, phone
INTO bname, phone
FROM beauty
WHERE id = bid;
END //
DELIMITER ;
CALL get_phone(2, @bname, @phone);
SELECT @bname, @phone;
# 3. Create stored procedure date_diff(), Realize the introduction of two goddess birthdays , Return date interval size
DELIMITER //
CREATE PROCEDURE date_diff(IN adate datetime, IN bdate datetime, OUT res int)
BEGIN
SELECT DATEDIFF(adate, bdate)
INTO res;
END //
DELIMITER ;
DROP PROCEDURE date_diff;
SET @birth1 = '1992-09-08';
SET @birth2 = '1989-01-03';
CALL date_diff(@birth1, @birth2, @result);
SELECT @result;
# 4. Create stored procedure format_date(), Pass in a date , Format as xx year xx month xx And return to
DELIMITER //
CREATE PROCEDURE format_date(IN para datetime, OUT res varchar(30))
BEGIN
SELECT CONCAT(YEAR(para), ' year ', MONTH(para), ' month ', DAY(para), ' Japan ')
INTO res;
END //
DELIMITER ;
SET @paraDate = '1992-12-15';
CALL format_date(@paraDate, @res);
SELECT @res;
# 5. Create stored procedure beauty_limit(), According to the incoming starting index and number of entries , Query the records of the goddess table
# Create a inout Stored procedure of mode parameters
DELIMITER //
CREATE PROCEDURE beauty_limit(IN startIndex int, IN size int)
BEGIN
SELECT *
FROM beauty
LIMIT startIndex , size;
END //
DELIMITER ;
CALL beauty_limit(1, 3);
# 6. Pass in a and b Two values , Final a and b All double and return
DELIMITER //
CREATE PROCEDURE add_pro(INOUT a double, INOUT b double)
BEGIN
SET a = a * 2;
SET b = b * 2;
END //
DELIMITER ;
SET @a = 5.5;
SET @b = 3.3;
CALL add_pro(@a, @b);
SELECT @a, @b;
# 7. Delete title 5 Stored procedure
DROP PROCEDURE IF EXISTS beauty_limit;
# 8. Check the title 6 Information about stored procedures in
SHOW CREATE PROCEDURE add_pro;
7.2 Exercise2
-- 5.2 Exercise2
# 0. preparation
USE test15_pro_func;
CREATE TABLE employees
AS
SELECT *
FROM study_mysql.employees;
CREATE TABLE departments
AS
SELECT *
FROM study_mysql.departments;
# Return without reference
# 1. Create a function get_count(), Number of employees returned to the company
DELIMITER //
CREATE FUNCTION get_count()
RETURNS int
DETERMINISTIC
CONTAINS SQL
BEGIN
RETURN (SELECT COUNT(*) FROM employees);
END //
DELIMITER ;
SELECT get_count();
# You can go back to
# 2. Create a function ename_salary(), According to the name of the employee , Return its wages
DELIMITER //
CREATE FUNCTION ename_salary(ename varchar(20))
RETURNS double
DETERMINISTIC
CONTAINS SQL
BEGIN
RETURN (SELECT salary
FROM employees
WHERE last_name = ename);
END //
DELIMITER ;
SELECT ename_salary('abel');
# 3. Create a function dept_sal() , According to the Department name , Return the average wage of the Department
DELIMITER //
CREATE FUNCTION dept_sal(did int)
RETURNS decimal(10, 2)
DETERMINISTIC
CONTAINS SQL
BEGIN
RETURN (SELECT AVG(salary)
FROM employees
GROUP BY department_id
HAVING department_id = did);
END //
DELIMITER ;
SELECT dept_sal(90);
# 4. Create a function add_float(), The implementation passes in two float, Return to the sum of the two
DELIMITER //
CREATE FUNCTION add_float(num1 float, num2 float)
RETURNS float
NOT DETERMINISTIC
NO SQL
BEGIN
RETURN num1 + num2;
END //
DELIMITER ;
SELECT add_float(2,34);
边栏推荐
- Rethinking about MySQL query optimization
- 2: Chapter 1: understanding JVM specification 1: introduction to JVM;
- 2022.6.20-6.26 AI industry weekly (issue 103): new little life
- UART Application Design and Simulation Verification 2 - TX Module Design (Stateless machine)
- YML configuration, binding and injection, verification, unit of bean
- It is proved that POJ 1014 module is optimized and pruned, and some recursion is wrong
- Spécifications techniques et lignes directrices pour la sélection des tubes TVS et ESD - Recommandation de jialichuang
- Dynamic planning: robbing families and houses
- 98. Verify the binary search tree ●●
- AsyncSocket长连接棒包装问题解决
猜你喜欢
Hcip course notes-16 VLAN, three-tier architecture, MPLS virtual private line configuration
Go language introduction detailed tutorial (I): go language in the era
orgchart. JS organization chart, presenting structural data in an elegant way
rsync远程同步
保研笔记四 软件工程与计算卷二(8-12章)
Huawei simulator ENSP - hcip - MPLS experiment
Practice of concurrent search
Switching power supply buck circuit CCM and DCM working mode
STM32__ 06 - single channel ADC
保研笔记二 软件工程与计算卷二(13-16章)
随机推荐
C# 反射与Type
带外和带内的区别
poj 2762 Going from u to v or from v to u? (推断它是否是一个薄弱环节图)
Idea rundashboard window configuration
rsync远程同步
UVA11294-Wedding(2-SAT)
LeetCode——Add Binary
2022.6.20-6.26 AI industry weekly (issue 103): new little life
Rasa 3. X learning series -rasa 3.2.1 new release
开源crm客户关系统管理系统源码,免费分享
成为程序员的你,后悔了吗?
Use mapper: --- tkmapper
【原创】程序员团队管理的核心是什么?
Xinyuan & Lichuang EDA training camp - brushless motor drive
(4)UART应用设计及仿真验证2 —— TX模块设计(无状态机)
Difference between out of band and in band
424. The longest repeated character after replacement ●●
MySQL (1) -- related concepts, SQL classification, and simple operations
【LeetCode】5. Valid Palindrome·有效回文
Research notes I software engineering and calculation volume II (Chapter 1-7)