当前位置:网站首页>MySQL advanced part 1: stored procedures and functions
MySQL advanced part 1: stored procedures and functions
2022-07-05 06:13:00 【Dawnlighttt】
List of articles
Overview of stored procedures and functions
Stored procedures and functions are compiled in advance and stored in a database SQL Collection of statements , Calling stored procedures and functions can simplify a lot of work for application developers , Reduce data transfer between database and application server , It's good for improving the efficiency of data processing .
The difference between a stored procedure and a function is that the function must have a return value , And stored procedures don't have .
function : Is a process with a return value ;
The process : Is a function with no return value ;
Create stored procedure
CREATE PROCEDURE procedure_name ([proc_parameter[,...]])
begin
-- SQL sentence
end ;
Example :
delimiter $
create procedure pro_test1()
begin
select 'Hello Mysql' ;
end$
delimiter ;
DELIMITER
This keyword is used to declare SQL Statement separator , tell MySQL Interpreter , Whether the order has ended ,mysql Whether it can be carried out . By default ,delimiter It's a semicolon ;. In the command line client , If there's a line of command that ends with a semicolon , So when you return ,mysql The command will be executed .
Calling stored procedure
call procedure_name() ;
Look at the stored procedure
-- Inquire about db_name All stored procedures in the database
select name from mysql.proc where db='db_name';
-- Query the status information of the stored procedure
show procedure status;
-- Query the definition of a stored procedure
show create procedure test.pro_test1 \G;
Delete stored procedure
DROP PROCEDURE [IF EXISTS] sp_name ;
grammar
Stored procedures are programmable , It means that variables can be used , expression , Control structure , To complete more complex functions .
Variable
- DECLARE
adopt DECLARE You can define a local variable , This variable can only be used in BEGIN…END In block .
DECLARE var_name[,...] type [DEFAULT value]
Example :
delimiter $
create procedure pro_test2()
begin
declare num int default 5;
select num+ 10;
end$
delimiter ;
- SET
Direct assignment uses SET, You can assign constants or expressions , The specific syntax is as follows :
SET var_name = expr [, var_name = expr] ...
Example :
DELIMITER $
CREATE PROCEDURE pro_test3()
BEGIN
DECLARE NAME VARCHAR(20);
SET NAME = 'MYSQL';
SELECT NAME ;
END$
DELIMITER ;
It can also be done through select … into Method for assignment operation :
DELIMITER $
CREATE PROCEDURE pro_test5()
BEGIN
declare countnum int;
select count(*) into countnum from city;
select countnum;
END$
DELIMITER ;
if conditional
Grammatical structure :
if search_condition then statement_list
[elseif search_condition then statement_list] ...
[else statement_list]
end if;
demand :
According to the defined height variable , Determine the type of body the current height belongs to
180 And above ----------> Tall and tall
170 - 180 ---------> Standard figure
170 following ----------> Average figure
Example :
delimiter $
create procedure pro_test6()
begin
declare height int default 175;
declare description varchar(50);
if height >= 180 then
set description = ' Tall and tall ';
elseif height >= 170 and height < 180 then
set description = ' Standard figure ';
else
set description = ' Average figure ';
end if;
select description ;
end$
delimiter ;
Pass parameters
Grammar format :
create procedure procedure_name([in/out/inout] Parameter name Parameter type )
...
IN : This parameter can be used as input , That is, you need the caller to pass in a value , Default
OUT: This parameter is used as the output , That is, the parameter can be used as the return value
INOUT: It can be used as an input parameter , It can also be used as an output parameter
IN - Input
demand :
According to the defined height variable , Determine the type of body the current height belongs to
Example :
delimiter $
create procedure pro_test5(in height int)
begin
declare description varchar(50) default '';
if height >= 180 then
set description=' Tall and tall ';
elseif height >= 170 and height < 180 then
set description=' Standard figure ';
else
set description=' Average figure ';
end if;
select concat(' height ', height , ' The corresponding figure type is :',description);
end$
delimiter ;
OUT- Output
demand :
According to the incoming height variable , Get the body type of the current height
Example :
create procedure pro_test5(in height int , out description varchar(100))
begin
if height >= 180 then
set description=' Tall and tall ';
elseif height >= 170 and height < 180 then
set description=' Standard figure ';
else
set description=' Average figure ';
end if;
end$
call :
call pro_test5(168, @description)$
select @description$
Little knowledge
@description : This variable should be preceded by the name of the variable “@” Symbol , It's called the user session variable , On behalf of the whole conversation, he is useful , This is similar to a global variable .
@@global.sort_buffer_size : This adds... To the variable “@@” Symbol , be called System variables
case structure
Grammatical structure :
Mode one :
CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] ...
[ELSE statement_list]
END CASE;
Mode two :
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] ...
[ELSE statement_list]
END CASE;
demand :
Given a month , And then calculate the quarter in which you're in
Example :
delimiter $
create procedure pro_test9(month int)
begin
declare result varchar(20);
case
when month >= 1 and month <=3 then
set result = ' first quarter ';
when month >= 4 and month <=6 then
set result = ' The second quarter ';
when month >= 7 and month <=9 then
set result = ' The third quarter ';
when month >= 10 and month <=12 then
set result = ' In the fourth quarter ';
end case;
select concat(' The month you entered is :', month , ' , The month is : ' , result) as content ;
end$
delimiter ;
while loop
Grammatical structure :
while search_condition do
statement_list
end while;
demand :
Calculate from 1 Add to n Value
Example :
delimiter $
create procedure pro_test8(n int)
begin
declare total int default 0;
declare num int default 1;
while num<=n do
set total = total + num;
set num = num + 1;
end while;
select total;
end$
delimiter ;
repeat structure
Conditional loop control statements , Exit the loop when the conditions are met .
while Only when the conditions are met ,repeat If you meet the conditions, you exit the cycle .
Be careful
:UNTIL search_condition The end condition has no semicolon
Grammatical structure :
REPEAT
statement_list
UNTIL search_condition
END REPEAT;
demand :
Calculate from 1 Add to n Value
Example :
delimiter $
create procedure pro_test10(n int)
begin
declare total int default 0;
repeat
set total = total + n;
set n = n - 1;
until n=0 // Be careful : The end condition has no semicolon
end repeat;
select total ;
end$
delimiter ;
loop sentence
LOOP Implement a simple loop , The conditions for exiting the loop need to be defined with other statements , You can usually use LEAVE Statements for , The specific syntax is as follows :
[begin_label:] LOOP // to LOOP Loop alias
statement_list
END LOOP [end_label]
If not statement_list Add the statement to exit the loop , that LOOP Statements can be used to implement simple dead loops .
leave sentence
Used to exit from annotated process constructs , Usually and BEGIN … END Or loop together . Here is a use LOOP and LEAVE Simple example of , Exit loop :
delimiter $
CREATE PROCEDURE pro_test11(n int)
BEGIN
declare total int default 0;
ins: LOOP
IF n <= 0 then
leave ins;
END IF;
set total = total + n;
set n = n - 1;
END LOOP ins;
select total;
END$
delimiter ;
The cursor / cursor
Cursors are data types used to store query result sets , In stored procedures and functions, you can use cursors to cycle through the result set . The use of cursors includes the declaration of cursors 、OPEN、FETCH and CLOSE, The grammar is as follows .
Declaration cursor :
DECLARE cursor_name CURSOR FOR select_statement ; // declare cursor , encapsulation select Statement query results
OPEN cursor :
OPEN cursor_name ; // Open cursor , Before you can iterate
FETCH cursor :
FETCH cursor_name INTO var_name [, var_name] ... // Iteration cursor , Call once , Read a row of data in the cursor
CLOSE cursor :
CLOSE cursor_name ; // Close cursor
Example :
Initialization script :
create table emp(
id int(11) not null auto_increment ,
name varchar(50) not null comment ' full name ',
age int(11) comment ' Age ',
salary int(11) comment ' salary ',
primary key(`id`)
)engine=innodb default charset=utf8 ;
insert into emp(id,name,age,salary) values(null,' The Golden Lion ',55,3800),(null,' White browed eagle king ',60,4000),(null,' King of green winged bat ',38,2800),(null,' Dragon King in purple shirt ',42,1800);
-- Inquire about emp The data in the table , And show it line by line
create procedure pro_test11()
begin
declare e_id int(11);
declare e_name varchar(50);
declare e_age int(11);
declare e_salary int(11);
declare emp_result cursor for select * from emp; // The current cursor encapsulates select Result of query
open emp_result; // Start cursor
fetch emp_result into e_id,e_name,e_age,e_salary; // Get cursor data , And assign to variable
select concat('id=',e_id , ', name=',e_name, ', age=', e_age, ', The salary is : ',e_salary);
fetch emp_result into e_id,e_name,e_age,e_salary;
select concat('id=',e_id , ', name=',e_name, ', age=', e_age, ', The salary is : ',e_salary);
fetch emp_result into e_id,e_name,e_age,e_salary;
select concat('id=',e_id , ', name=',e_name, ', age=', e_age, ', The salary is : ',e_salary);
fetch emp_result into e_id,e_name,e_age,e_salary;
select concat('id=',e_id , ', name=',e_name, ', age=', e_age, ', The salary is : ',e_salary);
fetch emp_result into e_id,e_name,e_age,e_salary;
select concat('id=',e_id , ', name=',e_name, ', age=', e_age, ', The salary is : ',e_salary);
close emp_result; // Close cursor
end$
Through the loop structure , Get the data in the cursor :
DELIMITER $
create procedure pro_test12()
begin
DECLARE id int(11);
DECLARE name varchar(50);
DECLARE age int(11);
DECLARE salary int(11);
DECLARE has_data int default 1;
DECLARE emp_result CURSOR FOR select * from emp;
DECLARE EXIT HANDLER FOR NOT FOUND set has_data = 0; // Failure to get the data will trigger the handle , It means that when data cannot be retrieved , take has_data Set to 0, The statement must be declared after the cursor statement
open emp_result;
repeat
fetch emp_result into id , name , age , salary;
select concat('id by ',id, ', name by ' ,name , ', age by ' ,age , ', The salary is : ', salary);
until has_data = 0
end repeat;
close emp_result;
end$
DELIMITER ;
Storage function
Grammatical structure :
CREATE FUNCTION function_name([param type ... ])
RETURNS type
BEGIN
...
END;
Case study :
Define a storage function , The total number of records that the request satisfies the condition ;
delimiter $
create function count_city(countryId int)
returns int
begin
declare cnum int ;
select count(*) into cnum from city where country_id = countryId;
return cnum;
end$
delimiter ;
call :
select count_city(1);
select count_city(2);
边栏推荐
- Records of some tools 2022
- LeetCode 0108.将有序数组转换为二叉搜索树 - 数组中值为根,中值左右分别为左右子树
- 7. Processing the input of multidimensional features
- Multi screen computer screenshots will cut off multiple screens, not only the current screen
- Error ora-28547 or ora-03135 when Navicat connects to Oracle Database
- One question per day 1020 Number of enclaves
- 【Rust 笔记】15-字符串与文本(上)
- 4. 对象映射 - Mapping.Mapster
- redis发布订阅命令行实现
- LaMDA 不可能觉醒吗?
猜你喜欢
1.15 - 输入输出系统
LVS简介【暂未完成(半成品)】
SPI details
On the characteristics of technology entrepreneurs from Dijkstra's Turing Award speech
Sqlmap tutorial (1)
Full Permutation Code (recursive writing)
Data visualization chart summary (II)
Redis publish subscribe command line implementation
Introduction to LVS [unfinished (semi-finished products)]
Overview of variable resistors - structure, operation and different applications
随机推荐
Introduction and experience of wazuh open source host security solution
[rust notes] 14 set (Part 2)
leetcode-1200:最小绝对差
Control unit
Overview of variable resistors - structure, operation and different applications
Sword finger offer II 058: schedule
Scope of inline symbol
Traditional databases are gradually "difficult to adapt", and cloud native databases stand out
LeetCode 0107. Sequence traversal of binary tree II - another method
1040 Longest Symmetric String
【Rust 笔记】13-迭代器(下)
leetcode-6109:知道秘密的人数
【Rust 笔记】14-集合(上)
Leetcode-3: Longest substring without repeated characters
One question per day 1447 Simplest fraction
中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章
The difference between CPU core and logical processor
Is it impossible for lamda to wake up?
Arduino 控制的 RGB LED 无限镜
【Rust 笔记】15-字符串与文本(上)