当前位置:网站首页>Stored procedures in MySQL
Stored procedures in MySQL
2022-06-22 13:22:00 【Xiaotiantian 666】
A stored procedure is a section of a database that has been compiled and stored in advance SQL A collection of statements , Calling stored procedures 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 .
Stored procedures are very simple in mind , Database SQL Language level code encapsulation and reuse .
- characteristic
1、 encapsulation , Reuse
2、 Can receive parameters , You can also return data
3、 Reduce network interaction , Efficiency tips - establish
CREATE PROCEDURE Stored procedure name ([ parameter list ])
BEGIN
--SQL sentence
END;
Be careful : On the command line , Execute the procedure that created the stored procedure SQL when , You need to use keywords delimiter Appoint SQL The terminator of a statement .
- call
CALL name ([ Parameters ]); - see
# Query the stored procedure and status information of the specified database
SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA='xxx';
# Query the definition of a stored procedure
SHOW CREATE PROCEDURE Stored procedure name
- Delete
DROP PROCEDURE [IF EXISTS] Stored procedure name ;
Variable
- System variables
The system variable is MySQL Provided by the server , It's not user-defined , At the server level . Divided into global variables (GLOBAL)、 Session variables (SESSION).
see System variables
# See all system variables
SHOW [SESSION | GLOBAL] VARIABLES;
# Can pass like Find variables by fuzzy matching
SHOW [SESSION | GLOBAL] VARIABLES LIKE '...';
# View the specified variable
SELECT @@[SESSION | GLOBAL] System variable name ;
Set up System variables
SET [SESSION | GLOBAL] System variable name = value ;
SET [SESSION | GLOBAL] System variable name = value ;
Be careful :
If not specified SESSION/GLOBAL, The default is SESSION, Session variables .
mysql After range restart , The global parameters set will become invalid , In order not to fail , Can be in /etc/my.cnf Middle configuration .
- User defined variables
User defined variables are variables defined by users according to their needs , User variables need not be declared in advance , Use... Directly when using “@ Variable name ” Just use it . Its scope is the current session .
# assignment
SET @var_name1=expr1[,@var_name2=expr2...];
SET @var_name1:=expr1[,@var_name2:=expr2...];# Recommended use
SELECT @var_name:=expr1[,@var_name2:=expr2...];
SELECT Field name INTO @var_name FROM Table name ;# Assign the value of the query in the table to the variable .
# Use
SELECT @var_name;
Be careful : User defined variables do not need to be declared or initialized , Only the obtained value is NULL.
- local variable
A local variable is a variable that is defined as needed and takes effect locally , Before the visit , need DECLARE Statement . It can be used as local variables and input parameters in stored procedures , The scope of a local variable is in its declaration BEGIN …END block .
# Statement
DECLARE Variable name Variable type [DEFAULT ...];
# assignment
SET Variable name = value ;
SET Variable name := value ;
SELECT Field name INTO Variable name FROM Table name ...;
Variable types are database field types :INT、BIGINT、CHAR、VARCHAR、DATE、TIME etc. .
if Judge
grammar :
IF Conditions 1 THEN
...
ELSEIF Conditions 2 THEN # Optional
...
ELSE # Optional
...
END IF;
case
Grammar 1 :
CASE case_value
WHEN when_value1 THEN statement_list1
[WHEN when_value2 THEN statement_list2]...
[ELSE statement_list]
END CASE;
Grammar II :
CASE
WHEN search_condition1 THEN statement_list1
[WHEN search_condition THEN statement_list2]...
[ELSE statement_list]
END CASE;
while
while A loop is a conditional loop control statement . When the conditions are met , In the execution loop SQL sentence . The specific grammar is :
# Judge the conditions first , If the condition is true, Then execute logic , otherwise , Do not execute logic
WHILE Conditions DO
SQL Logic ...
END WHILE;
repeat
repeat Is a conditional loop control statement , Exit the loop when the conditions are met . The specific grammar is :
# First execute the logic , Then judge whether the logic meets , If meet , The exit . If not satisfied , Then go on to the next cycle
REPEAT
SQL Logic
UNTIL Conditions
END REPEAT;
loop
LOOP Implement a simple loop , If not SQL Add a condition to exit the loop in the logic , It can be used to realize a simple dead cycle .LOOP It can be used with the following two statements :
LEAVE: In combination with recycling , Exit loop .
ITERATE: Must be used in the loop , The function is to skip the remaining statements of the current loop , Go directly to the next cycle .
[begin_label:] LOOP
SQL Logic
END LOOP [end_label];
LEAVE label; # Exit the loop body of the specified tag
ITERATE label; # Go directly to the next cycle
example : take 1 To va1 Add even numbers between
create procedure p3(in va1 int)
begin
declare va2 int default 0;
sum:loop
if va1 <= 0
then leave sum;
elseif va1%2=1
then set va1 := va1 - 1;iterate sum;
end if;
set va2 := va2 + va1;
set va1 := va1 - 1;
end loop sum;
select va2;
end;
The cursor
The cursor (CURSOR) Is the data type used to store the query result set , In stored procedures and functions, cursors can be used to cycle through the results . The use of cursors includes the declaration of cursors 、OPEN、FETCH and CLOSE, The grammar is as follows .
- declare cursor
DECLARE Cursor name CURSOR FOR Query statement ; - Open cursor
PEN Cursor name ; - Get cursor record
FETCH Cursor name INTO Variable [, Variable ]; - Close cursor
CLOSE Cursor name ;
Condition handler Handler
The condition handler can be used to define the corresponding processing steps when problems are encountered in the execution of the process control structure .
grammar :
DECLARE handler_action HANDLER FOR condition_value [,condition_value]... statement;
handler_action
CONTINUE: Continue with the current program
EXIT: Terminate the execution of the current program
condition_value
SQLSTATE sqlstate_vallue: Status code , Such as 02000
SQLWARNING: Used to 01 At the beginning SQLSTATE Code abbreviation
NOT FOUND: All with 02 At the beginning SQLSTATE Code abbreviation
SQLEXCEPTION: All have not been SQLWARNING or NOT FOUND The captured SQLSTATE Code abbreviation
example : Get the name and major of the student in the student table .
create procedure p3(in uage int)
begin
declare uname varchar(20);
declare upro varchar(100);
declare u_cursor cursor for select name,profession from tb_user where age <= uage;
declare exit handler for not found close u_cursor;# Used to end the loop
drop table if exists tb_user_pro;
create table if not exists tb_user_pro(
id int primary key auto_increment comment ' Number ',
name varchar(20) not null comment ' full name ',
profession varchar(100) comment ' major '
)comment ' Professional watch ';
open u_cursor;
while true do
fetch u_cursor into uname,upro;
insert into tb_user_pro value (null,uname,upro);
end while;
close u_cursor;
end;
Parameters
| type | meaning | remarks |
|---|---|---|
| IN | This type of parameter is used as input , That is, when you need to call, pass in the value | Default |
| OUT | This type of parameter is used as 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 |
CREATE PROCEDURE Stored procedure name ([IN/OUT/INOUT] Parameter name Parameter type )
BEGIN
...
END;
example :85 The above points are excellent ,60~85 A pass ,60 The following are the failing grades 
边栏推荐
猜你喜欢

卸载MySQL 8

基于SSM的小区垃圾分类和运输管理系统,高质量毕业论文范例(可直接使用),源码,数据库脚本,项目导入运行视频教程,论文撰写教程

SSM based community garbage classification and transportation management system, high-quality graduation thesis example (can be used directly), source code, database script, project introduction and o

130. Surrounded Regions

leetcode 1579. Ensure that the graph can be completely traversed

leetcode 第 297 场周赛

MySQL 5.7 + Navicat download and installation tutorial (with installation package)

Leetcode game 297

AcWing 241 楼兰图腾(树状数组详解)

docker安装postgresql
随机推荐
leetcode 85. Max rectangle
240. Search a 2D Matrix II
Mysql中的锁
448. Find All Numbers Disappeared in an Array
RobotFramework中setUp的小技巧
MySQL中的存储过程
基于JSP的图书馆管理系统,包含源码,数据库脚本,项目运行视频教程,毕设论文撰写视频教程
RF5.0新内容速看
Fluentd is easy to get started. Combined with the rainbow plug-in market, log collection is faster
leetcode 854. String with similarity K
leetcode 968.监控二叉树
leetcode 99.恢复二叉搜索树
240. Search a 2D Matrix II
Go language notes
Arcpy adding layers to map documents
leetcode LCP 10. 二叉树任务调度
leetcode 854. 相似度为 K 的字符串
leetcode 第 297 场周赛
从零开始写一个契约测试工具
257. Binary Tree Paths