当前位置:网站首页>MySQL 05 stored procedure
MySQL 05 stored procedure
2022-07-27 18:54:00 【A sea of clouds, a first thought】
MySQL 05 stored procedure
List of articles
- MySQL 05 stored procedure
- One 、 Learning goals
- Two 、 stored procedure
- 3、 ... and 、 Create stored procedure
- Four 、 Variables in stored procedures
- 5、 ... and 、MySQL Variable
- 6、 ... and 、 User variables are passed between stored procedures
- 7、 ... and 、Navicat Created in 、 Calling stored procedure
- 8、 ... and 、 Set user permission to execute stored procedures
- Nine 、 Viewing the status of stored procedures
- Ten 、 Look at the creation code of the stored procedure
- 11、 ... and 、 Modify stored procedure
- Twelve 、 Delete stored procedure
- 13、 ... and 、 Control statement of stored procedure
- fourteen 、IF-ELSEIF-ELSE Conditional statements
- 15、 ... and 、CASE Conditional statements
- sixteen 、WHILE Loop statement
- seventeen 、LOOP Loop statement
- eighteen 、REPEAT Loop statement
- nineteen 、 Iteration statement
- twenty 、 Summary of this chapter
One 、 Learning goals
- Understand the concept of stored procedures
- Will create 、 modify 、 Delete 、 View stored procedures
- Master the flow control statements of stored procedures
Two 、 stored procedure
2.1 Why do I need to use stored procedures
problem :
- Online bookstore Application , Different publishers need to count their book sales every month , And hope to store the data in the temporary table for analysis .
Basic steps
- Use DROP Statement to delete existing temporary table data
- Set the publisher name
- Get the number of the publishing house according to the name of the publishing house
- Query the sales data of the current month according to the publishing house number , And use the query results to create a new temporary table
analysis :
- Each step requires a SQL sentence
- Check the book sales of different publishers , You need to dynamically set the name of the publishing house
- Perform the same operation for data analysis every month
- In order to solve this problem more conveniently , have access to MySQL Of
stored procedure2.2 What is stored procedure
Stored Procedure
It's a group of people who do certain functions SQL Statement set
After compilation, it is saved in the database
By specifying the name of the stored procedure and giving the value of the parameter
MySQL5.0 The version starts to support stored procedures , Make the database engine more flexible and powerful
With parameters , You can also return the result
It can contain data manipulation statements 、 Variable 、 Logic control statements, etc
2.3 Advantages and disadvantages of stored procedures
advantage
- Reduce network traffic
- Improve execution speed
- Reduce the number of database connections
- High safety
- High reusability
shortcoming
- Poor portability
Experience
- In practical application development , Decide whether to use stored procedures according to business requirements , For particularly complex data processing in applications , You can choose stored procedures to implement
- for example : Complex report statistics , Joint queries involving multiple conditions and tables
3、 ... and 、 Create stored procedure
3.1 Grammar and characteristics :
grammar :
CREATE PROCEDURE The process of ([ Process parameters [,…]]) [ characteristic ] # optional , Used to set the behavior of stored procedures Stored procedure bodyCommon features :
characteristic explain LANGUAGE SQL Represents stored procedure language , Default SQL {CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA} Indicates the type of work to be done by the stored procedure The default value is CONTAINS SQL SQL SECURITY { DEFINER | INVOKER } Specify the execution permission of the stored procedure The default value is DEFINER •DEFINDER: Use the permissions of the creator •INVOKER: With the authority of the executor COMMENT ‘string’ Annotation information of stored procedure Example :
- Writing stored procedures , Output the total number of patients
# Delete... If it exists drop procedure if exists proc_patient_countPatient; # Create stored procedure create procedure proc_patient_countPatient() begin # The process body starts select count(0) as totalCount from patient; end # The process body endsproblem :
- The compiler treats it as normal SQL Statement processing , Error will be reported in compilation , What do I do ?
3.2 Declaration statement separator
- Use DELIMITER Keyword set the delimiter to “$$” or “//”
DELIMITER $$ # perhaps DELIMITER //
- Revert to the default separator “;”
DELIMITER ;3.3 Identification of process body
- When defining the body of a stored procedure , Need to identify the beginning and end
BEGIN # … END DELIMITER ; #END after , You have to use DELIMITER The delimiter set in the statement is endmatters needing attention :
// If no delimiter is declared , The compiler will treat it as normal SQL Statement processing , An error will be reported during compilation // Proper use : First use DELIMITER Keyword declares the separator of the current segment , Finally, restore the delimiter to the default characterExample :
# Delete... If it exists drop procedure if exists proc_patient_countPatient; delimiter// # Declaration separator create procedure proc_patient_countPatient() begin # The process body starts select count(0) as totalCount from patient; end// # The process body ends delimiter; # Restore the default delimiter # call call proc_patient_countPatient();3.4 Stored procedure parameter settings
Define the parameters of the stored procedure
grammar :
[IN | OUT | INOUT] Parameter name data typeExample :
DELIMITER // # Declaration separator CREATE PROCEDURE proc_patient_countPatient2(OUT patientNum INT) # Omit ... DELIMITER ; # Restore the default separatorBe careful :
- If you need to define more than one parameter , Need to use “,” separation
IN: Refers to input parameters
- The value of this parameter must be specified when calling the stored procedure
- This parameter can be used in stored procedures , But it cannot be returned
OUT: Refers to the output parameter
- This parameter can be changed in the stored procedure , And can return
INOUT: Refers to input and output parameters
- The value of this parameter is specified when calling the stored procedure
- Can be changed and returned in stored procedures
Call to execute stored procedure
CALL Stored procedure name ([ Parameters 1, Parameters 2, …]);Stored procedure calls are similar to Java Method calls in
call proc_patient_countPatient();3.5 establish 、 Call stored procedure example
- Use stored procedure query to obtain and output the total number of patients
delimiter // create procedure proc_patient_countPatient2(out patientCount int) begin select count(0) into patientCount from patient; end // delimiter ; # Call and output the total number of patients call proc_patient_countPatient2(@patientCount); select @patientCount as ' Total number of patients ';
Four 、 Variables in stored procedures
- And Java Language is similar to , Variables can be used when defining stored procedures
DECLARE Variable name [, Variable name ...] data type [DEFAULT value ];
- Assign values to variables
SET Variable name = Expression value [, Variable name = expression ...] ;
- Declare the transaction time variable trade_time, And set the default value to 2020-07-10
DECLARE trade_time date DEFAULT '2020-07-10';
- Set a variable total The value of is 100
SET total=100;
- matters needing attention :
When defining a stored procedure , The declaration of all local variables must be placed at the beginning of the stored procedure body ; otherwise , Will prompt grammatical errors
5、 ... and 、MySQL Variable
System variables
- finger MySQL Global variables , With “@@” start , In the form of “@@ Variable name ”
User defined variables
local variable
- Commonly used in SQL In the statement block of , Such as : In a stored procedure BEGIN and END Sentence block
- The scope is limited to the statement block that defines the variable
- The life cycle is also limited to the call period of the stored procedure
- In stored procedures Execute to END when , Local variables will be released
Session variables
- It is a variable maintained by the server for each client connection , And MySQL The client is bound
- Also known as User variables
- Values can be temporarily stored , And pass it to others in the same connection SQL Statement to use
- When MySQL When the client connection exits , User variables will be released
- When creating user variables , General with “@” start , In the form of “@ Variable name ”
MySQL Variable examples
demand :
- Create stored procedure , Through the department number and patient name entered by the user , Query the last examination time of the patient in the Department
analysis :
- Input parameters : Department number and patient name
- Output parameters : The last examination time of the patient in the Department
- The last examination time of the specified patient in the Department is obtained by dynamic query according to the entered parameter value
Define stored procedures :
delimiter // create procedure proc_exam_GetLastExamDateByPatientNameAndDepID (in patient_name varchar(50), in dep_id int,out last_exam_date datetime) begin declare patient_id int; # Declare local variables select patientid into patient_id from patient where patientname= patient_name; select patient_id; # Output patient's id # Use SELECT INTO Statement can assign values to multiple variables at once select max(examdate) into last_exam_date from prescription where patientid = patient_id and depid = dep_id; end // delimiter ;Calling stored procedure :
# Set user variables @patientName by ' Xia Ying ' set @patientName=' Xia Ying '; # Set user variables @dep_id by 1 set @dep_id=1; # Calling stored procedure call proc_exam_GetLastExamDateByPatientNameAndDepID (@patientName,@dep_id,@last_exam_date); # Output the last examination time of the patient in a department select @last_exam_date;
6、 ... and 、 User variables are passed between stored procedures
User variables can not only be in stored procedures and MySQL Set in the client , You can also pass values between different stored procedures
- Create stored procedure proc1, Set the user variable and assign it “ Wang Ming ”
- Create another stored procedure proc2, Output the assigned user variable information
# The transfer of user variables between two stored procedures # Create stored procedure proc1 delimiter // create procedure `proc1`( ) begin set @name = ' Wang Ming '; end // delimiter ; # Create stored procedure proc2 delimiter // create procedure `proc2`( ) begin select concat('name:',@name); end // delimiter ;
7、 ... and 、Navicat Created in 、 Calling stored procedure
Navicat Provides a good development environment , Than MySQL Command line operation is more convenient
The basic steps of creating and invoking stored procedures
Create stored procedure
- Right click... Under the selected database “ function ” node , Select... From the pop-up drop-down menu “ New function ”
- In the right area, it will be automatically created Stored procedure template , And write stored procedure code in it
Run stored procedures
- Click on “ preservation ” Button , The stored procedure will be automatically saved in the selected database “ function ” Under the node
- Click on “ function ” Button calls stored procedure
- According to the definition of stored procedure , Enter the set user parameter value in the pop-up dialog box
- Click on “ determine ” Button , Execute stored procedures , And output the result
matters needing attention :
Stored procedure templates are automatically added DEFINER Assignment statement
Navicat in , When writing stored procedures, you do not need to use DELIMITER Declare a new delimiter
8、 ... and 、 Set user permission to execute stored procedures
adopt DEFINER and SQL SECURITY Features control the execution permission of stored procedures
grammar :
CREATE [DEFINER = { user | CURRENT_USER }] # Definition DEFINER, Default to current user PROCEDURE Stored procedure name [SQL SECURITY { DEFINER | INVOKER } | …]# Appoint DEFINER or INVOKER jurisdiction BEGIN … ENDDEFINER
- Default DEFINER = CURRENT_USER
- Check ‘user_name’@‘host_name’ Authority
INVOKER
- When executing a stored procedure , The caller's permission will be checked
matters needing attention :
- If omitted sql security characteristic , Then use definer Property specifies the caller , And the caller must have EXECUTE jurisdiction , Must be in mysql.user In the table
- If you will sql security The property is specified as invoker, be definer attribute invalid
Example :
# For stored procedures p1 Users with execution permission can call it create definer = 'admin'@'localhost' procedure p1() sql security definer begin update t1 set counter = counter + 1; end;
- ‘admin’@‘localhost’ Users must also have p1 The execution authority of and data table t1 Of UPDATE jurisdiction , To execute the stored procedure ; Otherwise, the execution fails
# Call to execute stored procedure p2 Depends on the caller's permissions create definer = 'admin'@'localhost' procedure p2() sql security invoker begin update t1 set counter = counter + 1; end;
- If the caller does not have permission to execute the stored procedure or does not have access to the data table t1 Of UPDATE jurisdiction , The stored procedure call fails
Nine 、 Viewing the status of stored procedures
View the stored procedures that have been created in the database
grammar :
show procedure status;see hosptal Stored procedures created in the database
# Specify the database name to query the stored procedure show procedure status where DB = 'hospital';# Use LIKE Keyword matches the stored procedure name show procedure status like '%patient%';
Ten 、 Look at the creation code of the stored procedure
View the stored procedure code created in the database
SHOW CREATE PROCEDURE Stored procedure name ;View stored procedures “proc_patient_countPatient” Create code for
show create procedure proc_patient_countPatient;
11、 ... and 、 Modify stored procedure
Use ALTER PROCEDURE Statement to modify the properties defined when creating a stored procedure
ALTER PROCEDURE Stored procedure name [ characteristic ……] ;Store procedure proc_patient_countPatient Of SQL SECURITY Change the property to INVOKER
alter procedure proc_patient_countPatient sql security invoker;Experience
- Use ALTER Keywords can only modify the characteristics of stored procedures , If you want to modify the contents of the procedure body in the stored procedure , You need to delete the stored procedure first , Re create
- stay Navicat in , After modifying the contents of the stored procedure , It can be saved directly
Twelve 、 Delete stored procedure
Use DROP PROCEDURE Statement to delete the created stored procedure
DROP PROCEDURE Stored procedure name ;Delete the created stored procedure proc_patient_countPatient
drop procedure if exists;Be careful :
- Before creating a stored procedure , have access to IF EXISTS Statement to check whether it already exists , If it doesn't exist , Then create
13、 ... and 、 Control statement of stored procedure
And Java The flow control statements of the language are similar ,MySQL Control statements provided
Conditional statements
- IF-ELSEIF-ELSE Conditional statements
- CASE Conditional statements
Loop statement
- WHILE loop
- LOOP loop
- REPEAT loop
Iteration statement
fourteen 、IF-ELSEIF-ELSE Conditional statements
grammar :
IF Conditions THEN Statement list [ELSEIF Conditions THEN Statement list ] [ELSE Statement list ] END IF;Example :
- According to the patient's family income , Refund medical expenses with different proportions of subsidies
- Annual household income 5000 If the amount is less than yuan, the total medical expenses of the current year will be refunded 20%
- Annual household income 10000 The following will be refunded to the total medical expenses of the current year 15%
- Annual household income 30000 The following will be refunded of the total medical expenses 5%
- 30000 Those who are more than RMB yuan or not registered will not enjoy the return of medical expenses
- Enter the patient number and year , Calculate the refundable medical expenses of the patient in the current year
# Example 10: Calculate the returned medical expenses obtained by the patient create definer=`root`@`localhost` procedure `proc_income_calSubsidy` (in i_patientid int ,in i_year varchar(10), out o_subsidy float) begin declare t_totalCost float; declare t_income float default -1; select sum(checkItemCost) into t_totalCost from prescription p1 inner join checkitem on p1.checkItemID = checkitem.checkItemID where patientID = i_patientID and examDate >= concat(i_year,'-01-01') and examDate <= concat(i_year,'-12-31'); select income into t_income from subsidy where patientID = i_patientID; # Calculate the return amount according to the rules if t_income >=0 and t_income < 5000 then set o_subsidy = t_totalcost * 0.2; elseif t_income >= 5000 and t_income < 10000 then set o_subsidy = t_totalcost * 0.15; elseif t_income >= 10000 and t_income < 30000 then set o_subsidy = t_totalcost * 0.05; else set o_subsidy = 0; end if; end
15、 ... and 、CASE Conditional statements
grammar 1:
CASE WHEN Conditions THEN Statement list [WHEN Conditions THEN Statement list ] [ELSE Statement list ] END CASE;grammar 2:
CASE Name WHEN Conditional value THEN Statement list [WHEN Conditional value THEN Statement list ] [ELSE Statement list ] END CASE;Example :
# Example 11: Use CASE Realize the calculation of the returned medical expenses obtained by patients create definer=`root`@`localhost` procedure `proc_income_calsubsidy` (in i_patientid int ,in i_year varchar(10), out o_subsidy float) begin declare t_totalcost float; declare t_income float default -1; select sum(checkitemcost) into t_totalcost from prescription p1 inner join checkitem on p1.checkitemid = checkitem.checkitemid where patientid = i_patientid and examdate >= concat(i_year,'-01-01') and examdate <= concat(i_year,'-12-31'); select income into t_income from subsidy where patientid = i_patientid; # Calculate the return amount according to the rules case when t_income >=0 and t_income < 5000 then set o_subsidy = t_totalcost * 0.2; when t_income < 1000 then set o_subsidy = t_totalcost * 0.15; when t_income < 30000 then set o_subsidy = t_totalcost * 0.05; when t_income >= 30000 or t_income < 0 then set o_subsidy = 0; end case; endBe careful : In some cases ( for example , Make an equivalent judgment ), Using the second way of writing is more concise, but , because CASE There are column names behind , There will be some restrictions on the function
sixteen 、WHILE Loop statement
First, judge whether the condition is true . If set up , Then execute the loop body
[label:] WHILE Conditions DO Statement list END WHILE [label]
- label Label , Used to distinguish between different loops , Omission
- Use in begin、repeat、while perhaps loop Statement before
Suppose there is a test table test, Yes Id Field 、Val Field
According to the number of lines entered , Batch insert test data
seventeen 、LOOP Loop statement
There is no need to judge the initial conditions , Directly execute the loop body
[label:] LOOP Statement list END LOOP [label] ;encounter LEAVE sentence , Exit loop
leave lableExample :
- Inspection items , The name of the examination item is gastroscope 、 Enteroscope and bronchofibroscope , Insert in batches 3 The prices of the new items are 70 element
analysis :
- Save multiple inspection item names with strings , Input parameters as stored procedures
- Check the comma between item names “,” separation
LEAVE Statement leave label The program block identified by the label , Be similar to Java Of break sentence
# Example 13: Batch add inspection items create definer=`root`@`localhost` procedure `proc_checkitem_insert` ( in checkitems varchar(100)) begin declare comma_pos int; declare current_checkitem varchar(20); loop_label: loop set comma_pos = locate(',', checkitems); set current_checkitem = substr(checkitems, 1, comma_pos-1); if current_checkitem <> '' then set checkitems = substr(checkitems, comma_pos+1); else set current_checkitem = checkitems; end if; insert into checkitem(checkitemname,checkitemcost) values(current_checkitem,70); if comma_pos=0 or current_checkitem='' then leave loop_label; end if; end loop loop_label; end
eighteen 、REPEAT Loop statement
Execute the cycle operation first, and then judge the cycle condition
# And Java Of do-while Loop statements are similar to [label:] REPEAT Statement list UNTIL Conditions END REPEAT [label]And LOOP Compare loop statements
- The same thing : It does not need initial conditions to enter the circulation body directly
- Difference :REPEAT Statement can set exit conditions
Use REPEAT Loop statement coding implementation
- According to the number of lines entered , To the test table test Insert test data in medium batch
nineteen 、 Iteration statement
Return to the beginning of the block from the current code , Re execution
ITERATE label;
- ITERATE Keywords can be embedded in LOOP、WHILE and REPEAT In the program block
Input the number of data rows to be increased , The randomly generated test data must be greater than 0.5
delimiter // create definer=`root`@`localhost` procedure `proc_test_insert2`( in rows int) begin declare rand_val float; loop_label:while rows > 0 do select rand() into rand_val; if rand_val<0.5 then iterate loop_label; end if; insert into test values(null, rand_val); set rows = rows - 1; end while loop_label; end // delimiter ;
twenty 、 Summary of this chapter
边栏推荐
猜你喜欢

Idea 2020.1 Community Edition download experience

Hbuilder submission code

阿里p8总结的10条 SQL 优化方案(非常实用)

Full automatic breast pump chip dltap703sd

MySQL basic statement

LeetCode 刷题 第三天

Here are all the MySQL interview questions you can't expect (the latest version of 2022)

家用静音驱蚊灯芯片-DLTAP703SD-杰力科创

Electric heating neck pillow chip-dltap703sc

Wechat applet obtains openid, sessionkey, unionid
随机推荐
Product name fuzzy search:
面试官:你觉得你最大的缺点是什么?
瑞吉外卖笔记
订单的提交
Wechat applet multi file upload
JS中的数组与对象
LED带风扇护眼学习台灯触摸芯片-DLT8S12A
飞机大战英雄出场加子弹实现
Visual studio code installation tutorial (super detailed)
Interceptor拦截器
Led with fan eye protection learning table lamp touch chip-dlt8s12a
[NPM] the "NPM" item cannot be recognized as the name of cmdlets, functions, script files or runnable programs. Please check the spelling of the name. If the path is included, make sure the path is co
filebeat.yml配置文件关于多个服务的配置问题
Using Jieba and pyhanlp tools to extract keyword words and sentences
Whole body multifunctional massage instrument chip-dltap602sd
瑞吉外卖sql表
Canvas draws graphics according to coordinate points
Matplotlib (basic usage)
Solve the problem of JSP cascading
Talking about JVM (frequent interview)



