MySQL Advanced Query and Programming Notes• [Chapter 4 MySQL Programming]

All chapters >>>>


Contents of this chapter

4.1 User-defined variables

4.1.1 User session variables

4.1.2 User session variable assignment

4.1.3 Reset command end tag

4.1.4 Practice exercises

4.2 Stored Procedure

4.2.1 Local variables

4.2.2 Introduction to stored procedures

4.2.3 Syntax for creating and executing stored procedures

4.2.4 Stored procedure without parameters

4.2.5 Stored procedure with input parameters

4.2.7 Practice exercises

4.3 Conditional control statements

4.3.1 if statement

4.3.2 case statement

4.3.3 Usage of exists subquery

4.3.3 while statement

4.3.4 leave statement

4.3.5 iterate statement

4.3.6 Practice exercises

4.4 Cursor

4.4.1 Introduction to cursors

4.4.2 Steps to use cursors in MySQL

4.4.3 The use of cursors

4.4.4 Practice exercises

to sum up


4.1 User-defined variables

4.1.1 User session variables

User-defined variables are used to store temporary variables generated during the operation of MySQL stored procedures, which are divided into user session variables and local variables

User Session Variable (User Session Variable) is a variable defined by the MySQL client every time a MySQL client establishes a new connection with the MySQL server. This variable is closely related to the "current session"

MySQL user session variables start with an "@" and are not case sensitive. Under normal circumstances, the definition and assignment of user session variables will be carried out at the same time

Use the set command and select statement to define and assign user session variables. The syntax format of using the set command to define user session variables is as follows

grammar:

set @user_variable1=expression1[,@user_variable2=expression2, …]

user_variable1, user_variable2 are user session variable names; expression1, expression2 can be constants, variables and expressions

Example:

Use the set command to create MySQL user session variables @user_name and @age, and assign values ​​to them, and then use the select statement to output the values ​​of the above variables

set @user_name= ' 张三 ';
set @age=18;
select @user_name, @age;
set @age=@age+1;
select @user_name, @age;

The syntax format of using select statement to define user session variables is as follows

grammar:

第一种:“select @user_variable1:=expression1[,@user_variable2:=expression2, ... ]”

第二种:“select expression1 into @user_variable1, expression2 into @user_variable2, ...”

The difference between the first syntax format and the second syntax format is:

The select statement in the first grammatical format will produce a result set, and the select statement in the second grammatical format is only used for the definition and assignment of session variables, but will not produce a result set.

Example:

Use the select statement to create the MySQL user session variable @user_name and assign a value to it, and then use the select statement to output the value of the variable

select @user_name:='zhangsan';
select @user_name;
select'zhangsan'into @user_name;
select @user_name;

4.1.2 User session variable assignment

When retrieving data, if the result set of the select statement is a single value, the return result of the select statement can be assigned to the user session variable

Example:

Count the quantity of products and services of "Lingju.com", and assign the quantity to the user session variable @productNum, and output the value of the variable

Method 1: set+ subquery

set @productNum=(select count(*) from product)
select @productNum

Method 2: select+ subquery

select @productNum:=(select count(*) from product)

Method 3: Remove the simplified form of the subquery (most common)

select @productNum:=count(*) from product (简化形式 1)
select count(*) into @productNum from product(简化形式 2)
select count(*) from product into @productNum(简化形式 3)

4.1.3 Reset command end tag

There are usually multiple MySQL expressions in the begin-end statement block, and each MySQL expression uses ";" as the end tag

When entering MySQL commands or SQL statements on the MySQL client, the MySQL client also uses ";" as the end tag of the MySQL command by default

Since multiple MySQL expressions in the begin-end statement block are inseparable, in order to prevent these MySQL expressions from being disassembled, it is necessary to reset the command end tag of the MySQL client, also known as the command delimiter (delimiter)

By resetting the end tag of the command, the category information of goods and services is displayed, and the p_categoryID of the category is empty

Example:

delimiter $$
select * from category where p_categoryID is null $$
delimiter ;
select * from category where p_categoryID is null;

4.1.4 Practice exercises

 

4.2 Stored Procedure

4.2.1 Local variables

Local variables (local variables) must be defined in stored procedures, such as functions, stored procedures, triggers, and events, and the scope of local variables is limited to stored procedures. If you leave the stored program, local variables will have no meaning at all

grammar:

declare 局部变量 数据类型 ;
declare price decimal(8,2); declare address varchar(20);

Local variables are mainly used in the following 3 occasions

Scenario 1: When a local variable is defined between the begin-end statement blocks of a stored program, the local variable must be defined by the declare command first, and its data type must be specified. Only after defining a local variable, can you use the set command or select statement to assign a value to it.

Scenario 2: When a local variable is used as a parameter of a stored procedure or function, although it is not necessary to use the declare command to define, it is necessary to specify the data type of the parameter.

Scenario 3: Local variables can also be used in SQL statements in stored procedures. During data retrieval, if the result set of the select statement is a single value, the return result of the select statement can be assigned to a local variable. Local variables can also be directly embedded in the expressions of select statements, insert statements, update statements, and delete statements

4.2.2 Introduction to stored procedures

A stored procedure is a set of SQL statements to complete a specific function, compiled and stored in the database

The user invokes and executes it by specifying the name of the stored procedure and given parameters (if the stored procedure has parameters).

A stored procedure is actually a programmable function (the function has a return value, the stored procedure does not), it is created and stored in the database, and is composed of SQL statements and some special control structures.

When you want to perform the same function on different applications or platforms, or encapsulate specific functions, using stored procedures is a very practical solution

The advantages of stored procedures mainly include the following 5 points

  • Enhanced the functionality and flexibility of the SQL language
  • After the stored procedure is created, it can be called multiple times in the program without having to rewrite the stored procedure
  • SQL statements can achieve faster execution speed
  • Can reduce network traffic can also be used as a security mechanism

4.2.3 Syntax for creating and executing stored procedures

The syntax format of creating a stored procedure is as follows

grammar:

create procedure 存储过程名字 (
  [in|out|inout] 参数 1 数据类型 1,
  [in|out|inout] 参数 2 数据类型 2,        ……
 )
[no sql | reads sql data | modifies sql data]
begin
  存储过程语句块 ;
end;

The syntax description is as follows:

The parameters of the stored procedure are local variables.

in stands for input parameter (default is in parameter), which means that the value of this parameter must be specified by the calling program.

out stands for the output parameter, which means that after the calculation of the stored procedure, the calculation result of the out parameter is returned to the calling program.

Inout represents both an input parameter and an output parameter, indicating that the value of the parameter can be specified by the calling program, and the calculation result of the parameter can be returned to the calling program.

The syntax format for executing a stored procedure is as follows

grammar:

call  存储过程名 ( 参数列表 )

If the stored procedure has parameters, you need to pass in parameters, out parameters, or inout parameters to the stored procedure

4.2.4 Stored procedure without parameters

Example:

Create a stored procedure named proc_product_info, which will obtain the title, type name, group purchase price, area name and store name of all products, and display them in ascending order of type and group purchase price

begin      
select title, categoryName, currentPrice, areaName, shopName from product p,
category c, Area a, Shop s where p.categoryID=c.categoryID and p.areaID=a.areaID and p.shopID=s.shopID order by categoryName, currentPrice;
end
$$
delimiter ;

Click "Tools" "Command Line Interface" in Navicat For MySQL, and the MySQL command line interface appears. Enter the creation code of the above stored procedure in this interface, and press Enter to successfully create the stored procedure proc_product_info

You can see proc_product_info in the "Function" of Navicat For MySQL, indicating that proc_product_info has been created successfully. Click the stored procedure that needs to be operated, such as proc_product_info, and click "Design Function" to edit the code of the stored procedure

The two ways to run the stored procedure are as follows

  • In the edit window of the stored procedure, click "Run"
  • Enter "call stored procedure name" on the MySQL command line, in this case "call proc_product_info;"

Example:

Create a stored procedure named proc_ProductStatistics, which will obtain the number and average group purchase price of different types of goods and services

begin
select categoryName 商品类型名 , count(p.productID) 商品数量 , avg(currentPrice)
平均团购价 from product p, category c where p.categoryID=c.categoryID
group by categoryName order by 平均团购价 ;
end
$$
delimiter ;

4.2.5 Stored procedure with input parameters

Example:

Create a stored procedure named proc_OrdersGivenCustomer, which will obtain the order information of the specified customer after the specified date, request to output the customer name, order number, order date, product title and group purchase price, and display them in ascending order of order number and group purchase price

delimiter $$
create procedure proc_OrdersGivenCustomer(
in _customerName varchar(20),
in _ordersDate date
) 

Two input parameters are required: one is used to receive customer information (this title is customer name); the other is used to receive the specified date

reads sql data
begin
select customerName 客户姓名 , o.ordersID 订单号 , ordersDate 下单日期 ,
title 商品标题 , currentPrice 团购价
from customer c, orders o, ordersDetail od, product p
where c.customerID=o.customerID and o.ordersID=od.ordersID
and od.productID=p.productID and c.customerName=_customerName
and ordersDate>_ordersDate order by o.ordersID, currentPrice;
end
$$
delimiter ;

Execute the stored procedure to obtain the order information of the customer named "Lei Yabo" after March 31, 2019, and execute the stored procedure proc_OrdersGivenCustomer

set @customerName= ' 雷亚波 ';
set @ordersDate= '2019-3-31 ';
call proc_OrdersGivenCustomer(@customerName, @ordersDate);

When executing a stored procedure with parameters, the type, number, and order of the incoming values ​​need to correspond to the parameters defined in the stored procedure one by one.

If you need a stored procedure to return one or more values, you can do so by using output parameters. Output parameters must be declared using the out keyword when creating a stored procedure

Example:

Create a stored procedure named proc_MaxPriceGivenCategory, which will get the highest group purchase price of the specified type of goods

delimiter $$
create procedure proc_MaxPriceGivenCategory(
_categoryName varchar(20),
out _maxPrice decimal   )

Two parameters need to be defined: one is the input parameter, used to receive the information of the specified product type (this title is the type name); the other is the output parameter, used to output the highest group purchase price of the specified type of product

reads sql data
begin
select max(currentPrice) into _maxPrice from product p, category c
where p.categoryID=c.categoryID and categoryName=_categoryName;
end
$$
delimiter ;

Execute the stored procedure

set @categoryName=' 火锅 ';
call proc_MaxPriceGivenCategory(@categoryName, @maxPrice);
select concat(@categoryName,' 火锅类商品的最高团购价是 ',@maxPrice,' 元 ') 显示结果 ;

4.2.7 Practice exercises

 

4.3 Conditional control statements

4.3.1 if statement

MySQL provides simple flow control statements, including conditional control statements and loop statements. These flow control statements are usually used in the begin-end statement block

There are two types of conditional control statements: one is an if statement and the other is a case statement

The if statement determines the execution of different statement blocks according to the value of the conditional expression

grammar:

if 条件表达式 1 then 语句块 1;
[elseif 条件表达式 2 then 语句块 2]…
[else 语句块 n]
end if;

Create a stored procedure of proc_MaxPriceGivenCategory2, which will obtain the highest group purchase price of the specified type of goods, and display relevant information according to the different ranges of the highest group purchase price

  • If the price is greater than or equal to 100, it shows "high price"
  • If the price is greater than or equal to 50 and less than 100, it shows "moderate price"
  • For other prices, it will show "low price"

 

delimiter $$
create procedure proc_MaxPriceGivenCategory2(
_categoryName varchar(20),
out _maxPrice decimal,
out _message varchar(20) -- 信息显示
)
reads sql data
begin
select max(currentPrice) into _maxPrice from product p, category c
where p.categoryID=c.categoryID and categoryName=_categoryName;
if	_maxPrice>=100	then	set _message=' 价格高昂 ';
elseif	_maxPrice>=50 and _maxPrice<100	then	set _message=' 价格适中 ';
else	set _message=' 价格低廉 ';		
end if;
end
$$
delimiter ;

Execute the stored procedure

set @categoryName = ' 火锅 ';
call proc_MaxPriceGivenCategory2(@categoryName, @maxPrice, @message);
select concat(@categoryName, ' 火锅类商品的最高团购价是 ',@maxPrice, ' 元,',@message) 结果显示 ;

4.3.2 case statement

The case statement is used to implement more complex conditional judgments than the if statement branch

grammar:

case
  when  表达式 1  then 语句块 1
  when  表达式 2  then 语句块 2
  …
  else 语句块 n
end;

Get the average group purchase price of each type of product, and display relevant information according to the different ranges of the highest group purchase price

  • If the price is greater than or equal to 100, it shows "high price"
  • If the price is greater than or equal to 50 and less than 100, it shows "moderate price"
  • For other prices, it will show "low price"

4.3.3 Usage of exists subquery

select categoryName 类型 , avg(currentPrice) 平均团购价 ,
case
when avg(currentPrice)>=100 then ' 价格高昂 '
when avg(currentPrice)>=50 and avg(currentPrice)<100 then ' 价格适中 '
else ' 价格低廉 '
end ' 价格范围 '
from product p, category c
where p.categoryID=c.categoryID group by categoryName

4.3.3 while statement

When the value of the conditional expression is true, the loop body is executed repeatedly until the value of the conditional expression is false

grammar:

[ 循环标签 :]while 条件表达式 do
  循环体 ;
end while[ 循环标签 ];

Achieve accumulation from 1 to 50

declare total int default 0;
declare num int default 0;
while num<=50 do
set total=total +num;
set num=num+1;
end while;
select total;

4.3.4 leave statement

The leave statement is used to jump out of the current loop statement, such as the while statement, which is equivalent to the break statement in high-level programming languages

grammar:

leave 循环标签 ;

Achieve accumulation from 1 to 50

declare total int default 0;
declare num int default 0;
add_num: while true do
if(num>50) then
leave add_num;
end if;
set total=total+num;    set num=num+1;
end while add_num;

4.3.5 iterate statement

The iterate statement is used to jump out of this loop and proceed to the next loop. Its function is equivalent to the continue statement in a high-level programming language

grammar:

iterate 循环标签 ;

Achieve accumulation from 1 to 50

declare sum int default 0;
declare num int default 0;
add_num: while true do
if(num%2=0) then
set sum=sum+num;
else
set num=num+1;
iterate add_num;
end if;
set num=num+1;
if(num>50) then
leave add_num;
end if;
end while add_num;

4.3.6 Practice exercises

 

4.4 Cursor

4.4.1 Introduction to cursors

When database developers write stored procedures and other stored procedures, they sometimes need to use the SQL code in the stored procedures to scan the data in the select result set and require some simple processing for each record in the result set. Such problems can be solved by the cursor mechanism of the database

The cursor is essentially a mechanism that can extract one record at a time from the select result set, so the cursor is closely related to the select statement

In real life, when looking for someone's phone number in the phone book, you may use your "hand" to scan each line line by line to help us find the number we need. This situation is very similar to the cursor model, that is, the "phone book" is like a query result set, and the "hand" is similar to a cursor

4.4.2 Steps to use cursors in MySQL

The use of the cursor can be summarized as four steps: declaring the cursor, opening the cursor, extracting data from the cursor, and closing the cursor

To declare a cursor, you need to use the declare statement

grammar:

open 游标名 ;

After the cursor is opened with the open statement, the select statement corresponding to the cursor will be executed, and the result set corresponding to the select statement will be stored in the memory of the MySQL server.

To fetch data from the cursor, you need to use the fetch statement

grammar:

fetch 游标名 into 变量名 1, 变量名 2 , … ;

The number and types of variable names must be consistent with the number and types of fields in the select statement result set used when declaring the cursor.

When the fetch statement is executed for the first time, the first record will be extracted from the result set, and when the fetch statement is executed again, the second record will be extracted from the result set...and so on, the fetch statement will only extract one record from the result set each time , So the fetch statement needs the cooperation of the loop statement to achieve the traversal of the entire result set.

When the fetch statement is used to fetch the last record from the cursor, and the fetch statement is executed again, the error message "error 1329(0200): no data to fetch" will be generated. Database developers can customize error handlers for MySQL error code 1329 to end the traversal of the result set.

Close the cursor needs to use the close statement

grammar:

close 游标名 ;

The function of closing the cursor is to release the result set generated when the cursor is opened, thereby saving the memory space of the MySQL server. If the cursor is not explicitly closed, it will be closed at the end of the begin-end block that was opened.

4.4.3 The use of cursors

Example:

In order to promote consumption, the merchants marketing on "Youle.com" intend to discount 5% off orders with a single consumption amount of more than 100 yuan (including 100 yuan)

(1) Connect the order list and the product table to calculate the amount of each order

select ordersID, sum(currentPrice*quantity) 金额 from ordersdetail od, product p
where od.productID=p.productID group by ordersID

(2) Use a subquery to generate the amount of each order in the order table

update orders o join
(select ordersID, sum(currentPrice*quantity) 金额 from ordersdetail od, product p
where od.productID=p.productID group by ordersID) A
on o.ordersID=A.ordersID set amount=A. 金额

(3) Write a stored procedure in which a cursor whose query result set is the amount of all orders is generated. By traversing each order in the cursor result set, the order amount that meets the conditions (the amount is not less than 100) can be updated to achieve demand

delimiter $$
create procedure proc_AmountDiscount()
modifies sql data
begin
declare _ordersID int;
declare _amount decimal(10,2);
declare state varchar(20);
declare amount_cursor cursor for select ordersID, amount from orders;
-- 错误处理程序的定义必须放在所有变量及游标定义之后,并且放在其他所有 MySQL 表达式之前
declare continue handler for 1329 set state='error';
open amount_cursor;
discount:while true do
fetch amount_cursor into _ordersID, _amount;
if(state='error') then
leave discount;
end if;

(4) Execute the stored procedure "call AmountDiscount;" to adjust the order amount of a single consumption of more than 100 yuan (including 100 yuan) to 95% of the original price.

if(_amount>=100) then
update orders set amount=amount*0.95 where ordersID=_ordersID;
end if;
end while discount;
close amount_cursor;
end
$$
delimiter ;

4.4.4 Practice exercises

 

to sum up

  • Use the set command and select statement to define and assign user session variables
  • When creating a stored procedure, the database developer needs to provide information such as the name of the stored procedure, the parameters of the stored procedure, and the statement block of the stored procedure (a series of SQL statements)
  • Use "call stored procedure name (parameter list)" to execute the stored procedure
  • MySQL provides simple flow control statements, including conditional control statements and loop statements. These flow control statements are usually used in the begin-end statement block
  • The use of the cursor can be summarized as four steps: declaring the cursor, opening the cursor, extracting data from the cursor, and closing the cursor

 

Guess you like

Origin blog.csdn.net/weixin_44893902/article/details/111105187