当前位置:网站首页>MySQL stored procedure
MySQL stored procedure
2022-07-05 12:13:00 【ziyi813】
MySQL stored procedure
summary
What is stored procedure ?
A stored procedure is a set of SQL Statements set , Powerful , It can realize some complex logic functions , It's the database SQL Language level code closure and reuse .
What are the characteristics ?
There are input and output parameters , You can declare variables , Yes IF、ELSE,while Wait for the control statement , By writing stored procedures , It can realize complex logic functions ; Common features of functions , modularization , encapsulation , Code using , Fast , Only the first execution needs to be compiled and optimized , Subsequent calls can be executed directly , Omit compilation .
Format
delimiter Custom end symbol
create procedure Storage name ( [in, out, inout] Parameter name data type ...)
begin
sql sentence
end Custom end symbol
delimiter;
Example 1:
-- Example 1
delimiter $$
create procedure proname1()
begin
select dname, ename from employee;
end $$
delimiter;
-- Calling stored procedure
call proname1()
Variable
Direct variable :
-- Variable
delimiter $$
create procedure p2()
BEGIN
declare var1 varchar(20) default 'aaa'; -- Create variables
set var1 = 'setname'; -- Assign a value to a variable
select var1; -- Output variables
end $$;
delimter ;
call p2();
Query statement variables :
You can also use select into Statement to assign a value to a variable , Query results can only output single row and single column .
select col_name [...] into val_name[,...]
from table_name where condition
Example :
-- Query statement variables
delimiter $$
create procedure p3()
BEGIN
declare var2 varchar(20) default ''; -- Create variables
select ename into var2 from employee where eid = '1001'; -- Assign a value to a variable
select var2; -- Output variables
end $$;
delimiter ;
call p3();
User variables
User customization , The current session is valid .
grammar :
@var_name, There is no need to state in advance , Use to declare
Example :
-- User variables
delimiter $$
create procedure p4()
BEGIN
set @var_name1 = 'litchi';
end $$
call p4() $$
select @var_name1 $$;
System variables
System variables are divided into global variables and session variables
The global variable is in MYSQL The startup time is automatically initialized by the server to the default value , These default values can be changed by my.ini This file to change .
Session variables every time a new connection is established , from MYSQL To initialize the ,MYSQL The values of all current global variables will be copied , As a conversation variable .
in other words , If you're building After the conversation , The values of session variables and global variables have not been changed manually , Then all the variable values are the same .
difference :
The difference between a global variable and a session variable is , Changes to global variables affect the entire server , But changes to session variables , It only affects the current conversation ( That is, the current database connection )
Global variables
Grammar format :
@@global.var_name
The operation sample :
-- Global variables
show global variables;
-- View a global variable
select @@global.auto_increment_increment;
-- Modify the value of the global variable
set global sort_buffer_size = 40000; -- 262144
-- Query global variables
select @@global.sort_buffer_size;
Session variables
-- Session variables
show session variables;
-- View a session variable
select @@session.auto_increment_increment;
-- Modify session variables
set session sort_buffer_size = 60000;
-- View modification
select @@session.sort_buffer_size;
Stored procedure parameters
IN key word
in Represents the parameter passed in , You can pass in values or variables , Even if you pass in a variable , Does not change the value of the variable , It can be updated internally , It only works within the scope of the function .
Example :
-- Encapsulated with parameters Stored procedure , Pass in the employee number , Find employee information
delimiter $$
create procedure dec1(in param_eid varchar(20))
begin
select * from employee where eid = param_eid;
end $$;
delimiter ;
call dec1(1001);
-- Example multi parameter
delimiter $$
create procedure dec2(in param_dname varchar(20), in param_salary int(10))
begin
select * from employee where dname = param_dname and salary > param_salary;
end $$;
delimiter ;
call dec2(' Shu Kingdom ', 5000);
OUT key word
out Efferent
Example :
-- Pass in the employee number , Return employee name
delimiter $$
create procedure dec3(in param_eid int(10), out out_ename varchar(20) )
begin
select ename into out_ename from employee where eid = param_eid;
end $$;
delimiter ;
call dec3(1001, @ename);
select @ename;
-- Pass in the employee number , Return employee name and salary
delimiter $$
create procedure dec4(in param_eid int(10), out out_ename varchar(20), out out_salary decimal(10,2) )
begin
select
ename, salary into out_ename, out_salary
from employee where eid = param_eid;
end $$;
delimiter ;
call dec4(1001, @ename, @salary);
select @ename;
select @salary;
INOUT
inout Indicates the parameter passed in from the outside Variables that can be returned after modification , That is, you can pass in the value of the variable or modify the value of the variable ( Even if the function is finished )
Example :
-- Pass in a number , Returns the of this number 10 times
delimiter $$
create procedure dec5(inout num int)
begin
set num = num * 10;
end $$
delimiter ;
set @inout_num = 20;
call dec5(@inout_num);
select @inout_num;
-- Incoming employees ID, Return department number , Salary , Annual salary
delimiter $$
create procedure dec6(inout inout_ename varchar(20), inout inout_salay int(20) )
begin
select concat_ws(",", eid, ename, salary ) into inout_ename from employee where ename = inout_ename;
set inout_salay = inout_salay * 12;
end $$
delimiter ;
set @inout_ename = ' Liu bei ';
set @inout_salay= 3000;
call dec6(@inout_ename, @inout_salay);
select @inout_ename;
select @inout_salay;
Process control judgment
IF sentence
IF Statement contains multiple conditional judgments , According to the result TRUE, FALSE Execute statement ,
Grammar format :
if search_condition then statement_list
[elseif search_condition_2 then statement_list_2] ...
[else statement_list_n]
end if
Code example :
-- Example of control flow 1
delimiter $$
create procedure dec7(in score int)
BEGIN
if score < 60
then
select " fail, ";
elseif score >= 60 and score < 90
then
select " good ";
elseif score >= 90 and score <= 100
then
select " good ";
ELSE
select " Abnormal grades ";
end if;
end $$
delimiter ;
set @score = 60;
call dec7(90)
select @score;
CASE sentence
-- grammar 1
case case_value
when when_value then statement_list
[when when_value then statement_list] ...
[else statement_list]
end case
-- grammar 2
case
when search_condition then statement_list
[when search_condition then statement_list] ...
[else statement_list]
end case
Loop statement
while, repeat, loop
while Format
[ label :] while The loop condition do
The loop body :
end while [ label ]
Cycle control
leave similar break, Jump out of , End the current cycle
iterate Be similar to continue, continue , End this cycle and continue to the next
repeat
[ label :] repeat
Circular book ;
until Conditional expression
end repeat [ label ];
The cursor cursor
The cursor (cursor) Is the data type used to store the query result set , In stored procedures and functions, you can use the cursor to cycle the result set , The use of cursors includes the declaration of cursors 、OPEN、FETCH and CLOSE
Format :
-- Declarative grammar
declare cursor_name cursor for select_statement
-- Open syntax
open cursor_name
-- Value Syntax
fetch cursor_name into var_name [, var_name] ...
-- Turn off Syntax
close cursor_name
exception handling
边栏推荐
- 【yolov3损失函数】
- The solution of outputting 64 bits from printf format%lld of cross platform (32bit and 64bit)
- Riddle 1
- codeforces每日5题(均1700)-第五天
- [pytorch pre training model modification, addition and deletion of specific layers]
- Sentinel sentinel mechanism of master automatic election in redis master-slave
- Redirection of redis cluster
- 手机 CPU 架构类型了解
- Ncp1342 chip substitute pn8213 65W gallium nitride charger scheme
- 【SingleShotMultiBoxDetector(SSD,单步多框目标检测)】
猜你喜欢
pytorch-权重衰退(weight decay)和丢弃法(dropout)
Sentinel sentinel mechanism of master automatic election in redis master-slave
[yolov5.yaml parsing]
全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
Matlab label2idx function (convert the label matrix into a cell array with linear index)
互联网公司实习岗位选择与简易版职业发展规划
Master the new features of fluent 2.10
pytorch-softmax回归
Use and install RkNN toolkit Lite2 on itop-3568 development board NPU
Understand kotlin from the perspective of an architect
随机推荐
leetcode:1200. Minimum absolute difference
Complete activity switching according to sliding
Codeforces Round #804 (Div. 2)
Automated test lifecycle
[untitled]
yolov5目標檢測神經網絡——損失函數計算原理
Linux安装部署LAMP(Apache+MySQL+PHP)
谜语1
Video networkState 属性
Yolov5 target detection neural network -- calculation principle of loss function
[HDU 2096] 小明A+B
Codeforces Round #804 (Div. 2)
1. Laravel creation project of PHP
Codeworks 5 questions per day (1700 average) - day 5
abap查表程序
IPv6与IPv4的区别 网信办等三部推进IPv6规模部署
[yolov3 loss function]
Pytorch softmax regression
【ijkplayer】when i compile file “compile-ffmpeg.sh“ ,it show error “No such file or directory“.
pytorch-softmax回归