Database stored procedures and functions

MySQL stored procedures and stored functions

MySQL provides stored procedure ( procedure ) and stored function ( function ) mechanisms, we first collectively call them stored procedures, general SQL statements need to be compiled and then executed, and stored procedures are a set of SQL statements to complete specific functions. After compilation, it is stored in the database, and it will be executed when the user calls it by specifying the name of the stored program and giving parameters (if the stored program has parameters).

Advantages and disadvantages of stored procedures

advantage

Often stored procedures help improve application performance. When created, stored procedures are compiled and stored in the database. However, MySQL implements stored procedures slightly differently. MySQL stored procedures are compiled on demand. After compiling a stored procedure, MySQL puts it in the cache. MySQL maintains its own cache of stored procedures for each connection. If the application uses the stored procedure multiple times in a single connection, use the compiled version, otherwise the stored procedure works like a query.

1) Performance: Stored procedures help reduce the traffic between the application and the database server, because the application does not have to send multiple lengthy SQL statements, but only the name and parameters of the stored procedure.

2) Reuse: Stored programs are reusable and transparent to any application. Stored procedures expose the database interface to all applications so that developers do not have to develop functionality already supported in stored procedures.

3) Safe: Stored programs are safe. A database administrator can grant appropriate permissions to applications accessing stored procedures in a database without providing any permissions to the underlying database tables.

shortcoming

1) If you use a large number of stored procedures, then the memory usage per connection using these stored procedures will increase significantly.

Also, if you overuse a large number of logical operations in stored procedures, CPU usage will also increase because database servers are not designed to favor logical operations.

2) It is difficult to debug stored procedures. Only a few database management systems allow debugging of stored procedures. Unfortunately, MySQL does not provide the ability to debug stored procedures.

database stored procedure

1. The concept of stored procedure

A stored procedure is a subroutine code defined on the server, and a stored procedure is one of the database objects.

The stored procedure runs on the server side and is called when needed. The execution speed is fast and easy to use. It
ensures the security of the database. The stored procedure can complete all database operations. It
reduces the network load and the client does not need to submit SQL statements
. It can accept user parameters and return parameters.

Two, stored procedure type

System stored procedure [name prefixed with sp, stored in the master library]
Local stored procedure [stored in a user-defined database]
Extended stored procedure [names are prefixed with xp, stored in the master library]
Temporary stored procedure [name Starting with #]

3. Create and call the stored procedure

Statement to create a stored procedure:

delimiter $$ //这是定义一个结束符$$
create procedure [存储过程名称]([参数])
begin
......
end$$
delimiter ; //重新定义结束符为 ;

Create a stored procedure that counts the number of courses:

create procedure count_course()
begin
select count(*) from course;
end$$

  • delimiter redefines the end symbol

Call the count_course stored procedure

call count_course$$

Fourth, stored procedure variables

1. Variable definition

Declare variables using declare

declare number1 int default 20;

A statement declares only one variable.
The scope is in the scope of begin...end
. The variable has the same data type and length as the SQL statement. You can also specify the default value, character set, and collation. Variables can be assigned
using set or select into

Create a test() stored procedure function to display the number of men and women:

create procedure test()
begin
declare boys int(10);
declare girls int(10);
select count(*) into boys from student where Ssex='男';
select count(*) into girls from student where Ssex='女';
select boys,girls;
end$$

Note that to return the variable value without parameters, you can use the select statement
insert image description here

2. The scope of variables

  • A function can have multiple begin...end blocks, and multiple begin...end blocks can be nested in a block
  • Variables defined in a function's parent block are available to all child blocks
  • Within a single begin...end block, variables are local and cannot be used across sibling blocks
  • Function incoming parameters are global variables and can be used in all blocks

Create a stored procedure function that displays a table showing the number of adults and minors and the maximum and minimum ages:

delimiter $$
create procedure age_count()
begin
	begin
		declare adult int;
		declare minor int;
		select count(*) into adult from student where Sage>=18;
		select count(*) into minor from student where Sage<18;
		select adult,minor;
	end;
	begin
		declare age_max int;
		declare age_min int;
		select max(Sage) into age_max from student;
		select min(Sage) into age_min from student;
		select age_max,age_min;
	end;
end$$
delimiter ;

  • At the end of each nested block, end should be added; sql end character
    insert image description here

After the variable is mentioned in the parent begin block, the variable can be used interchangeably between the two blocks

drop procedure age_count;
delimiter $$
create procedure age_count()
begin
	declare adult int;
	declare minor int;
	declare age_max int;
	declare age_min int;
	begin
		select count(*) into adult from student where Sage>=18;
		select count(*) into minor from student where Sage<18;
		select adult,age_min;
	end;
	begin
		select max(Sage) into age_max from student;
		select min(Sage) into age_min from student;
		select age_max,minor;
	end;
end$$
delimiter ;

insert image description here

Five, stored procedure parameters

The functions mentioned above have no parameters, and only use select to return the result set. The
parameters that the function can take are divided into: incoming parameters in, outgoing parameters out, incoming and outgoing parameters inout;

When the function does not specify the parameter type, the parameter passed in defaults to the in type

drop procedure findname;
delimiter $$
create procedure findname(sno int)
begin
	declare name varchar(10);
	select Sname into name from student where Sno=sno limit 1;
	select name;
end$$
delimiter ;

insert image description here

  • When using the select into statement to assign values, make sure that the statement returns only one result, or add limit 1 to limit the number of rows returned
  • SQL variable names cannot be the same as column names

Use the parameter output of the out type, the result should be consistent with the previous question

drop procedure findname;
delimiter $$
create procedure findname(in sno int,out sname varchar(10))
begin
	select Sname into sname from student where Sno=sno limit 1;
end$$
delimiter ;


call findname(2,@name);
select * @name;

insert image description here

6. Define conditions and define processing procedures

Definition conditions:
Define the problems that may be encountered during program execution in advance.
Handling procedures:
handle the defined problems accordingly, and ensure that the storage function can continue to execute when encountering warnings or errors, so as to avoid the abnormal stop of the program

Define conditions

declare [condition_name] condition for [错误码/错误值];
declare command_not_allowed condition for sqlstate '42000';//错误值
declare command_not_allowed condition for 42000;//错误码

handler

declare [handler_type] handler for [condition_name]
......

handler_type error handling method

mysql provides three values

  • continue //Do not handle errors, the stored function continues to execute

  • exit //Exit immediately when encountering an error

  • undo //Undo the operation before encountering an error

condition_name error type

condition_name can customize the error type, and mysql also has its own error type:

  • ​ sqlstate_value: a string error value containing 5 characters;
  • ​ condition_name: Indicates the name of the error condition defined by declare condition;
  • ​ SQLWARNING: Match all sqlstate error codes starting with 01;
  • ​ NOT FOUND: Match all sqlstate error codes starting with 02;
  • ​ SQLEXCEPTION: Matches all sqlstate error codes not caught by SQLWARNING or NOT FOUND;

7. Process control

SQL arithmetic operators

Suppose the value of variable a is: 10, and the value of variable b is: 20, the following are the execution results of each operator:
insert image description here

SQL comparison operators

Suppose the value of variable a is: 10, and the value of variable b is: 20, the following are the execution results of each operator:
insert image description here

SQL logical operators:

This is a list of all logical operators in SQL.
insert image description here

order of priority

Higher-level operators are evaluated before lower-level operators. In the table below, 1 represents the highest level and 8 represents the lowest level.
insert image description here

Conditional statements

(1) if statement

basic structure:

single conditional statement

begin
if(...)
then
	......
else
	......
	end if;
end$$

multiple conditional statement

begin
if(...)
then
	......
elseif(...)
then
	......
else 
	......
end if;

end$$

  • The if statement needs to have end if to end the if statement

Determine whether Cno has a null value

delimiter $$
CREATE PROCEDURE ifnull()
begin
	declare flag int;
	select count(*) into flag from student where Cno is null;
	if flag is null
		then select '没有空值' as '是否有空值';
		else select '仍有空值' as '是否有空值';
	end if;
end
delimiter ;

insert image description here

insert image description here

(2) case statement

The case statement can calculate multiple conditional expressions and return one of the qualified results

case [测试表达式]
when [测试值1] then [结果表达式1]
when [测试值2] then [结果表达式2]
when [测试值3] then [结果表达式3]
......
else [结果表达式0]
end


DROP PROCEDURE IF EXISTS testCase;
DELIMITER //
CREATE PROCEDURE testCase(OUT result VARCHAR(255))
BEGIN
     DECLARE val VARCHAR(255);
     SET val = 'a';
     CASE val IS NULL
         WHEN 1 THEN SET result = 'val is true';
         WHEN 0 THEN SET result = 'val is false';
         ELSE SELECT 'else';
     END CASE;
END //
DELIMITER ;
set @result='';
CALL testCase(@result);

According to the input course name, add a line of course category

create procedure course_cate(cid varchar(10))
begin
update course set cate=
case(select cname from course where Cid=cid)
when '语文' then '文科'
when '数学' then '理科'
else 'x'
end case
end

loop statement

(3) while statement

basic structure:

begin
	while([执行条件]) do
	......
	end while;
end;

Create a new Sscore column:

alter table student add Sscore int;

Randomly insert grades from 1 to 100 points, input parameter i as the number of people who need to modify grades, use while loop to modify grades line by line

drop procedure add_math_score();
delimiter $$
create procedure add_math_score(i int)
begin
	declare n int default 0;
	declare score int default 0;
	while(n<i) do
	begin
		set n=n+1;
		set score=floor(100*rand());
		select score ;
		update student set Sscore=score where Sno=n;
	end;
	end while;
end$$
delimiter ;

insert image description here

  • Modify the scores of the first 12 people as random numbers

(4) repeat UNTLL statement

The usage of the REPEATE...UNTLL statement is similar to the do...while statement in Java. It executes the loop operation first, and then judges the condition. The difference is that the loop operation is executed when the value of the REPEATE expression is false, and stops until the expression value is true.

basic structure

begin
	repeat
	......
	until [跳出条件]
	end repeat;
end;

Referring to the example of while, the result is the same

drop procedure add_math_score();
delimiter $$
create procedure add_math_score(i int)
begin
	declare n int default 0;
	declare score int default 0;
	repeat
	begin
		set n=n+1;
		set score=floor(100*rand());
		select score ;
		update student set Sscore=score where Sno=n;
	end;
	until n>=15
	end repeat;
end$$
delimiter ;

  • The difference between repeat and while lies in two points, one is the position where the condition is written, while is to write the loop condition at the beginning of the loop block, and repeat is to write at the end .
  • The second is the conditional statement. The while conditional statement is executed when it is true, and the repeat is to jump out when the conditional statement is true.
  • Which line of repeat's until does not add a semicolon;
-- 创建过程
DELIMITER $$
CREATE 
    PROCEDURE demo7(IN num INT,OUT SUM INT)
	BEGIN
	     SET SUM = 0;
	     REPEAT-- 循环开始
		SET num = num+1;
		SET SUM = SUM+num ;
		UNTIL num>=10
		END REPEAT; -- 循环结束
	END$$
DELIMITER;

CALL demo7(9,@sum);

SELECT @sum;

(5) loop statement

A loop statement is used to execute certain statements repeatedly.

During execution, the LEAVE statement or ITEREATE can be used to jump out of the loop, and judgment statements such as IF can also be nested.

  • The effect of the LEAVE statement is for the break in Java to terminate the loop;
  • The effect of the ITERATE statement is equivalent to continue in Java, which is used to skip this loop. Enter the next cycle. And the statement under ITERATE will not be in progress.

basic structure

begin
	[循环名称]:loop
		......
		if [跳出条件] then leave [循环条件];
		end if;
	end loop [循环条件];
end

Add student table data in batches:

drop procedure add_data();
delimiter $$
create procedure add_data(i int)
	begin
		declare flag int default 0;
		add_loop:loop
		set flag=flag+1;
			if flag>i then leave add_loop;
			end if;
		insert into student(Sname,Sno,Cno,Ssex,Sage,Sscore) values('批量人',flag+15,1002,'男',22,100);
		end loop add_loop;
	end
delimiter ;

insert image description here

DELIMITER $$
CREATE 
    PROCEDURE demo8(IN num INT,OUT SUM INT)
	BEGIN
	     SET SUM = 0;
	     demo_sum:LOOP-- 循环开始
		SET num = num+1;
		IF num > 10 THEN
		    LEAVE demo_sum; -- 结束此次循环
		ELSEIF num <= 9 THEN
		    ITERATE demo_sum; -- 跳过此次循环
		END IF;
		
		SET SUM = SUM+num;
		END LOOP demo_sum; -- 循环结束
	END$$
DELIMITER;

CALL demo8(0,@sum);

SELECT @sum;

Insert information using stored procedures

DELIMITER $$
CREATE 
    PROCEDURE demo9(IN s_student VARCHAR(10),IN s_sex CHAR(1),OUT s_result VARCHAR(20))
	BEGIN
	   -- 声明一个变量 用来决定这个名字是否已经存在
	   DECLARE s_count INT DEFAULT 0;
	   -- 验证这么名字是否已经存在
	   SELECT COUNT(*) INTO s_count FROM student WHERE `name` = s_student;	
	   IF s_count = 0 THEN
	        INSERT INTO student (`name`, sex) VALUES(s_student, s_sex);
		SET s_result = '数据添加成功';
	   ELSE
                SET s_result = '名字已存在,不能添加';
                SELECT s_result;
	   END IF;
	END$$
DELIMITER;

call this function

CALL demo9("Jim","女",@s_result);

insert image description here

insert image description here

Management of eight stored procedures

show stored procedure

SHOW PROCEDURE STATUS

insert image description here

Display stored procedures for a specific database

SHOW PROCEDURE STATUS WHERE db = 'db名字' AND NAME = 'name名字';

Show stored procedures for a specific schema

SHOW PROCEDURE STATUS WHERE NAME LIKE '%mo%';

insert image description here

Display the source code of the stored procedure

SHOW CREATE PROCEDURE 存储过程名;

insert image description here

delete stored procedure

DROP PROCEDURE 存储过程名;

Realization of calling stored procedures in the backend

In mybatis, call the stored procedure

<parameterMap type="savemap" id=“usermap"> 
	<parameter property="name" jdbcType="VARCHAR" mode="IN"/>
	<parameter property="sex" jdbcType="CHAR" mode="IN"/>
	<parameter property="result" jdbcType="VARCHAR" mode="OUT"/>
</parameterMap>

<insert id="saveUserDemo" parameterMap="savemap" statementType="CALLABLE"> 
{call saveuser(?, ?, ?)} 
</insert >

call database management

HashMap<String, Object> map = new HashMap<String, Object>(); 
	map.put("name", "Jim"); 
	map.put("sex","男");
	userDao.saveUserDemo(map); 
	map.get(“result”);//获得输出参数

stored function

function

Grammatical structures

CREATE FUNCTION存储函数名称(参数列表])
RETURNS type [characteristic ..]
BEGIN
-- SQL语句RETURN ...;
END ;

characteristic description

  • deterministic identical input parameters produce identical results
  • no sql does not contain sql statement
  • READS SQL DATA Contains statements that read data but not statements that write data

the case

  1. Define a storage function to obtain the number of students whose grades are greater than 95 in the student table
/*
	定义存储函数,获取学生表中成绩大于95分的学生数量
*/
DELIMITER $

CREATE FUNCTION fun_test1()
RETURNS INT
BEGIN
	-- 定义统计变量
	DECLARE result INT;
	-- 查询成绩大于95分的学生数量,给统计变量赋值
	SELECT COUNT(*) INTO result FROM student WHERE score > 95;
	-- 返回统计结果
	RETURN result;
END$

DELIMITER ;

-- 调用fun_test1存储函数
SELECT fun_test1();

-- 删除存储函数
DROP FUNCTION fun_test1;
  1. Calculate the value accumulated from 1 to n, where n is the parameter value passed in
create function fun1(n int)
returns int DETERMINISTIC
begin
	declare total int default 0;
	while n>0 do
		set total := total + n;
		set n := n - 1;
	end while;
	return total;
end;

select fun1(100);

  1. delete function
drop function 函数名;

The difference between stored procedures and functions

  1. Stored procedure users complete specific operations or tasks (such as insert, delete, etc.) in the database, and functions are used to return specific data
  2. The stored procedure declaration uses procedure,
  3. Stored procedures do not need a return type, functions must return a type
  4. The stored procedure can be executed independently, the function cannot be executed as an independent plsql, it must be part of the expression
  5. Stored procedures can only return values ​​through out and in/out. In addition to using out and in/out, functions can also use return to return values.
  6. The stored procedure cannot be called in the sql statement (DML or SELECT), but the function can

Different application scenarios

  • If you need to return multiple values ​​and no return value , use a stored procedure ; if you only need to return a value , use a function
  • Stored procedures are generally used to perform a specified action, and functions are generally used to calculate and return a value
  • You can call functions inside SQL to complete complex calculation problems, but you cannot call stored procedures

The return value is different

A stored function must have one and only one return value, and the numeric type of the return value must also be specified.

A stored procedure may or may not have a return value, or even have multiple return values.

The two methods of assignment are different:

Stored functions can be assigned using select ... into ... and set values, and can only use return to return the result set.

Stored procedures can use select to return result sets.

Use it differently:

Functions can be directly used in SQL statements and can be used to extend standard SQL statements.

Stored procedures need to be called separately using call, and cannot be embedded in SQL statements.

There are more restrictions on the function body in the function:

You cannot open transaction, commit, rollback, set autocommit=0, etc. explicitly or implicitly.

But stored procedures can use almost all sql statements.

Similarities between stored procedures and functions

  1. Encapsulates program logic to complete data processing operations
  2. Precompilation is faster than directly writing query statements
  3. Both can take parameters to meet the needs of data processing.
    Stored procedures do not need return types, and functions must return types
  4. The stored procedure can be executed independently, the function cannot be executed as an independent plsql, it must be part of the expression
  5. Stored procedures can only return values ​​through out and in/out. In addition to using out and in/out, functions can also use return to return values.
  6. The stored procedure cannot be called in the sql statement (DML or SELECT), but the function can

Different application scenarios

  • If you need to return multiple values ​​and no return value , use a stored procedure ; if you only need to return a value , use a function
  • Stored procedures are generally used to perform a specified action, and functions are generally used to calculate and return a value
  • You can call functions inside SQL to complete complex calculation problems, but you cannot call stored procedures

The return value is different

A stored function must have one and only one return value, and the numeric type of the return value must also be specified.

A stored procedure may or may not have a return value, or even have multiple return values.

The two methods of assignment are different:

Stored functions can be assigned using select ... into ... and set values, and can only use return to return the result set.

Stored procedures can use select to return result sets.

Use it differently:

Functions can be directly used in SQL statements and can be used to extend standard SQL statements.

Stored procedures need to be called separately using call, and cannot be embedded in SQL statements.

There are more restrictions on the function body in the function:

You cannot open transaction, commit, rollback, set autocommit=0, etc. explicitly or implicitly.

But stored procedures can use almost all sql statements.

Similarities between stored procedures and functions

  1. Encapsulates program logic to complete data processing operations
  2. Precompilation is faster than directly writing query statements
  3. Both can take parameters to meet the needs of data processing

The notes in this chapter are based on the information I found on the Internet and my own understanding. I hope it can help everyone. Thank you for your patience. If you have any mistakes, please contact me and I will correct them in time.

Guess you like

Origin blog.csdn.net/apple_67445472/article/details/131155670