当前位置:网站首页>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);
边栏推荐
- Leetcode-31: next spread
- 快速使用Amazon MemoryDB并构建你专属的Redis内存数据库
- Basic explanation of typescript
- Open source storage is so popular, why do we insist on self-development?
- 【Rust 笔记】14-集合(上)
- leetcode-6109:知道秘密的人数
- 【Rust 笔记】15-字符串与文本(上)
- Error ora-28547 or ora-03135 when Navicat connects to Oracle Database
- Bit mask of bit operation
- Navicat連接Oracle數據庫報錯ORA-28547或ORA-03135
猜你喜欢
Sqlmap tutorial (1)
MatrixDB v4.5.0 重磅发布,全新推出 MARS2 存储引擎!
LeetCode 0108.将有序数组转换为二叉搜索树 - 数组中值为根,中值左右分别为左右子树
Appium基础 — 使用Appium的第一个Demo
Appium automation test foundation - Summary of appium test environment construction
1.13 - RISC/CISC
Dynamic planning solution ideas and summary (30000 words)
LeetCode 0108. Convert an ordered array into a binary search tree - the median of the array is the root, and the left and right of the median are the left and right subtrees respectively
Spark中groupByKey() 和 reduceByKey() 和combineByKey()
Leetcode-6111: spiral matrix IV
随机推荐
927. Trisection simulation
Network security skills competition in Secondary Vocational Schools -- a tutorial article on middleware penetration testing in Guangxi regional competition
[rust notes] 14 set (Part 1)
Control unit
【Rust 笔记】16-输入与输出(上)
QQ电脑版取消转义符输入表情
In depth analysis of for (VaR I = 0; I < 5; i++) {settimeout (() => console.log (I), 1000)}
Sqlmap tutorial (1)
4. 对象映射 - Mapping.Mapster
1.13 - RISC/CISC
leetcode-31:下一个排列
Simply sort out the types of sockets
【Rust 笔记】15-字符串与文本(下)
多屏电脑截屏会把多屏连着截下来,而不是只截当前屏
leetcode-22:括号生成
Multi screen computer screenshots will cut off multiple screens, not only the current screen
Typical use cases for knapsacks, queues, and stacks
leetcode-6108:解密消息
New title of module a of "PanYun Cup" secondary vocational network security skills competition
2022 pole technology communication arm virtual hardware accelerates the development of Internet of things software