当前位置:网站首页>Knowledge points of MySQL (13)
Knowledge points of MySQL (13)
2022-07-28 12:23:00 【Flag: roll king!】
One 、 stored procedure
meaning : Is a set of precompiled SQL Encapsulation of statements .
Execution process : Stored procedures are pre stored in MySQL Server , When you need to perform , 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 )
- 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 , Views are virtual tables , Usually do not directly operate on the underlying data table , And stored procedures are programmed SQL, You can directly manipulate the underlying data table , Compared with the collection oriented operation , It can realize some more complex data processing .
1, classification

2, Creation and call of stored procedure
# preparation
create database dbtest15;
use dbtest15;
create table employees
as
select * from atguigudb.'employees';
create table departments
as
select * from atguigudb.'departments';
select * from employees;
select * from departments;
# Create stored procedure
delimiter $
create procedure select_all_data()
begin
select * from employees;
end $
delimiter;
# Calls to stored procedures
call select_all_data();Two 、 Storage function
Create and call storage functions
# 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)
# The way 1
deterministic #
contains sql # Function properties
reads sql data #
#
begin
return (select email from employees where last_name='Abel');
end //
delimiter;
# Calling the storage function
select email_by_name();
select email,last_name from employees where last_name='Abel';
# 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
# The way 2( Declare functions )
set global log_bin_trust_function_creators=1;
delimiter //
create function email_by_id(emp_id int)
returns varchar(25)
begin
return (select email from employees where employee_id=emp_id);
end //
delimiter;
# call
select email_by_id(101); # The way 1
set @emp_id :=102;
select email_by_id(@emp_id); # The way 2
# 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
begin
return (select count(*) from employees where department_id=dept_id);
end //
delimiter;
# call
set @dept_id :=30;
select count_by_id(@dept_id); Compare stored functions with stored procedures :
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 .
3、 ... and 、 View of stored procedures and functions \、 Modification and deletion
1, Storage function 、 View of stored procedure
1) Use show create Statement to view the creation information of stored procedures and functions
show create procedure Stored procedure name :
show create function Store function name ;
2) Use show status Statement to view the status information of stored procedures and functions
show procedure status like ' Stored procedure name ';
show function status like ' Store function name ';
3) from information_schema.routines View the stored procedure and function information in the table
select * from information_schema.routines where routine_name=' Store name ';
2, Storage function 、 Changes to stored procedures
Be careful : Modify stored procedures or functions , It does not affect the function of stored procedures or functions , Just modify the relevant features .
alter procedure stored procedure
SQL security invoker
comment ' Query maximum wage ';
3, Storage function 、 Deletion of stored procedure
drop function if exists Store function name ;
drop procedure if exists Stored procedure name ;
stored procedure :
advantage :
- Stored procedures can be compiled and used more than once
- It can reduce the development workload
- The security of stored procedure is strong
- It can reduce the amount of network transmission
- Good encapsulation
shortcoming :
- Poor portability
- Debugging difficulty
- Version management of stored procedures is difficult
- It is not suitable for high concurrency scenarios
Four 、LOOP、WHITE、REPEAT Three circulation structures
1,LOOP loop
LOOP Loop statements are used to repeat certain statements ,LOOP The statements in the loop are repeated until the loop is exited ( Use LEAVE Clause ), Jump out of the loop process .
# give an example 1
delimiter //
create procedure test_loop()
begin
# Declare local variables
declare num int default 1;
loop_label:loop
# Reassign
set num=num+1;
if num>=10 then leave loop_label;
end if;
end loop loop_label;
# see num
select num;
end //
delimiter;
# call
call test_loop();
# give an example 2: Declaring stored procedures “update_salary_loop()", Statement out Parameters num, Number of output cycles , Loop in the stored procedure to raise everyone's salary , Original 1.1 times , Until the average salary of the whole company reaches 12000 end , And count the number of cycles
delimiter //
create procedure update_salary_loop(out num int)
begin
# Declare variables
declare avg_sal double;
declare loop_count int default 0; # Record times
# Get the average salary of employees
select avg(salary) into avg_sal from employees;
loop_lab:loop
# End cycle condition
if avg_sal>=12000 then leave loop_lab;
end if;
# If lower 12000, Update the salary of personnel
update employees set salary =salary * 1.1;
# to update avg_sal The value of the variable
select avg(salary) into avg_sal from employees;
# Record the number of cycles
set loop_count=loop_count+1;
end loop loop_lab;
# to num assignment
set num=loop_count;
end //
delimiter;
# call
call update_salary_loop(@num);
select @num;
2,while loop
# give an example 1:
delimiter //
create procedure test_while()
begin
# Initialization conditions
declare num int default 1;
while num<=10 do
# Iteration conditions
set num=num+1;
end while;
# Inquire about
select num;
end //
delimiter;
# call
call test_while();
3,repeat loop
# give an example
delimiter //
create procedure test_repeat()
begin
# Declare variables
declare num int default 1;
repeat
set num=num+1;
until num>=10
end repeat;
# see
select num;
end //
delimiter ;
# call
call test_repeat(); Compare the three cycles :
LOOP: Generally used to implement simple ” die “ loop .
WHILE: Judge before you execute .
REPEAT: Execute before judge , Unconditionally execute at least once .
5、 ... and 、 The cursor ( Or the cursor )
Cursor let SQL This set oriented language has the ability of process oriented development
Steps for using cursors :
- declare cursor
- Open cursor
- Use cursors ( Get data from cursor )
- Close cursor
give an example 1: Create stored procedure “get_count_by_limit_total_salary()", Statement in Parameters limit_total_salary,double type : Statement out Parameters total_count,int type . The function can accumulate the salary values of several employees with the highest salary , Until the total salary reaches limit_total_salary The value of the parameter , Return the accumulated number of people to total_count.
delimiter //
create procedure get_count_by_limit_total_salary(in limit_total_salary double,out total_count int)
begin
# Declare variables
declare sum_sal double default 0.0; # Record the total accumulated salary
declare emp_sal double; # Record the salary of each employee
declare emp_count int default 0; # Record the cumulative number of people
# declare cursor
declare emp_cursor cursor for select salary from employees order by salary desc;
# Open cursor
open emp_cursor;
repeat
# Use cursors
fetch emp_cursor into emp_sal;
set sum_sal= sum_sal+ emp_sal;
set emp_count=emp_count +1;
until sum_sal >= limit_total_salary
end repeat;
set total_count =emp_count;
# Close cursor
close emp_cursor;
end //
delimiter;
# call
call get_count_by_limit_total_salary(200000,@total_count);
select @total_count;Summary : The cursor is MySQL An important function of , To read the data in the result set one by one , Provides the perfect solution , Compared with implementing the same function at the application level , Cursors can be used in stored programs , Efficient , The program is also more concise , But it needs to be closed after use , This can improve the overall efficiency of the system .
边栏推荐
- php保留两位小数的几种方法介绍
- Localization, low latency, green and low carbon: Alibaba cloud officially launched Fuzhou data center
- 使用百度飞桨 EasyDL 完成垃圾分类
- SQL injection LESS18 (header injection + error injection)
- Idea replication module
- Design process sharing of wireless anti loss alarm based on single chip microcomputer
- Saltstack command injection vulnerability analysis (cve-2020-16846)
- 用C语言开发NES游戏(CC65)10、游戏循环
- PHP日期时间运用:添加或减去特定日期的天数
- 数字经济时代的开源数据库创新 | 2022 开放原子全球开源峰会数据库分论坛圆满召开
猜你喜欢

laravel表单数据验证
![[real question of written examination]](/img/3f/e061df6a2c5c92429cfd3c69cc94ce.png)
[real question of written examination]

瑞吉外卖——Day01

Training mode and practice of digital applied talents in Colleges and Universities under the integration of industry and education
![[leetcode] 7. valid anagram · effective letter ectopic words](/img/bc/9806df1358c6f09db03ef2e771aa5a.png)
[leetcode] 7. valid anagram · effective letter ectopic words

Hcip (PAP authentication and chap authentication of PPP)

Is it difficult for cloud native machine learning to land? Lingqueyun helps enterprises quickly apply mlops

Alexnet - paper analysis and reproduction

分布式定时器

Docker runs MySQL service
随机推荐
新手如何快速完成建站?来免费“试衣间”体验
Hcip rip comprehensive experiment
[leetcode] 6. invert binary tree
Image filter from the perspective of convolution
[try to hack] UDF raises rights
Google Earth engine (GEE) -- problems in the use of coordinate projection and reduceresolution functions in image downscaling
Lua middle__ index、__ Understanding of newindex, rawget and rawset
IRBuilder
用C语言开发NES游戏(CC65)06、精灵
REST风格
Yolov3 complete explanation - from the perspective of data coding
Live: never believe that suffering is worth it. Suffering is suffering
Saltstack command injection vulnerability analysis (cve-2020-16846)
聚变云原生,赋能新里程 | 2022 开放原子全球开源峰会云原生分论坛圆满召开
PHP date time application: add or subtract the number of days of a specific date
laravel表单数据验证
分布式定时器
Top level "redis notes", cache avalanche + breakdown + penetration + cluster + distributed lock, Nb
Exploration on cache design optimization of community like business
php⽉份加减最简单的处理⽅法