The use of stored procedures and cursors-MySQL

What is a stored procedure?

 

You can understand it as a C language function that is a collection of operations. Only need to call this function to achieve the function of multiple statements

Stored procedures and functions are a collection of some SQL statements defined in the database, and then directly call these stored procedures and functions to execute the defined SQL statements. Stored procedures and functions can prevent developers from writing the same SQL statement repeatedly. Moreover, the stored procedures and functions are stored and executed in the MySQL server, which can reduce data transmission between the client and the server.

Create a stored procedure

Creating stored procedures and functions refers to combining a set of frequently used SQL statements together and storing these SQL statements as a whole in the MySQL server. Stored procedures can be divided into stored procedures and functions. The statement CREATE PROCEDURE used to create a stored procedure in MySQL. Its grammatical form is as follows:

CREATE PROCEDURE procedure_name([proc_param[,…]])    

         routine_body                                     

In the above statement, the parameter procedure_name indicates the name of the stored procedure to be created, the parameter proc_param indicates the parameters of the stored procedure, and the parameter routine_body indicates the SQL statement code of the stored procedure. You can use BEGIN...END to mark the beginning and end of the SQL statement.

Tip:  When creating a stored procedure, the name of the stored procedure cannot be the same as the name of an existing stored procedure. In actual combat, it is recommended that the name of the stored procedure be named procedure_xxx or proc_xxx.

The syntax form of each parameter in proc_param is as follows:

    [IN|OUT|INOUT] param_name type

In the above statement, each parameter consists of three parts, namely input/output type, parameter name and parameter type. Among them, there are three types of input/output types, namely IN (representing input type), OUT (representing output type), and INOUT (representing input/output type). param_name represents the parameter name; type represents the parameter type, which can be any data type supported by the MySQL software.

【demo】

mysql>   use school;    #Select database school                                             

mysql> DELIMITER $$                                                                                

mysql> create PROCEDURE  proc_delete_student (IN sid int )                                   

        BEGIN 

         declare cid int; #define variable cid                              

         Select class_id into cid from student where id = sid; #Set variables by query statement                                                                           

         delete from grade where id = sid; #Delete records in the grade table    

         delete from student where id = sid; #Delete    records in the student table                                                    

         update class set count=count-1 where id = cid; #Update the records in the class table   

        END;                                                                        

        $$                                                                           

         DELIMITER ;                                                                 

mysql>  call proc_delete_student(2); #Call a     stored procedure                                                           

  1. Use variables in stored procedures

In stored procedures and functions, you can define and use variables. Users can use the keyword DECLARE to define variables and then assign values ​​to the variables. The scope of these variables is in the BEGIN...END block.

1. Define variables

In MySQL, you can use the DECLARE keyword to define variables. The basic syntax for defining variables is as follows:

    DECLARE var_name[,…] type [DEFAULT value]   

Among them, the keyword DECLARE is used to declare variables; the parameter var_name is the name of the variable, and multiple variables can be defined at the same time; the parameter type is used to specify the type of the variable; the DEFAULT value clause sets the default value of the variable to value without using DEFAULT Clause, the default value is NULL.

Define the variable cid , the data type is INT, the default value is 10, the code is as follows:

  DECLARE cid INT DEFAULT 10;    

 

2. Assign values ​​to variables

In MySQL, you can use the keyword SET to assign values ​​to variables. The basic syntax of the SET statement is as follows:

    SET var_name=expr[,var_name=expr]…

Among them, the keyword SET is used to assign a value to a variable; the parameter var_name is the name of the variable; and the parameter expr is an assignment expression. A SET statement can assign values ​​to multiple variables at the same time, and the assignment statements of each variable are separated by commas.

For example, to assign the variable tmp_id to 88 , the code is as follows:

SET tmp_id = 88;

 

In MySQL, you can also use the SELECT...INTO statement to assign values ​​to variables. The basic syntax is as follows:

     SELECT col_name[,…] INTO var_name[,…]     

     FROM table_name WHERE condition         

Among them, the parameter col_name represents the name of the query field; the parameter var_name is the name of the variable; the parameter table_name refers to the name of the table; and the parameter condition refers to the query condition.

[Demo] Query the record with id 3 from the employee table, and assign the id value of the record to the variable tmp_id, the code is as follows:

    SELECT id INTO tmp_id

FROM grade WEHRE id=sid;

mysql>   use school;    #Select database school                                             

mysql>  drop  PROCEDURE if exists query_student_class_info;                                                                             

mysql> DELIMITER $$                                                                                

mysql> create procedure  query_student_class_info (IN sid int, OUT cname varchar(128), OUT ccount  int)                                   

        BEGIN   

            declare tmp_name varchar(128);

            declare tmp_count int;

            declare tmp_cid  int;

            select class_id into tmp_cid from student where id = sid;         

            select name, count into tmp_name, tmp_count from class where id = tmp_cid;

            set cname = tmp_name, ccount = tmp_count;

         END;    

         $$                                                                           

         DELIMITER ;                                                                 

mysql>  call query_student_class_info(4, @name, @count);    #调用存储过程  

mysql>  select @name, @count;                                                         

  1. 光标的使用

查询语句可能查询出多条记录,在存储过程和函数中使用光标来逐条读取查询结果集中的记录。有些书上将光标称为游标。光标的使用包括声明光标、打开光标、使用光标和关闭光标。光标必须声明在处理程序之前,并且声明在变量和条件之后。

1. 声明光标

在MySQL中,可以使用DECLARE关键字来声明光标,其基本语法如下:

    DECLARE cursor_name CURSOR         

    FOR select_statement;                  

其中,参数cursor_name表示光标的名称;参数select_statement表示SELECT语句的内容。

【demo】下面声明一个名为cur_student的光标,代码如下:

mysql>  use school;   #选择数据库school                                                                                                                         

mysql> DELIMITER $$                                                                                

mysql> create procedure  query_student (IN sid int, OUT cname varchar(128), OUT class_id  int )                                      

        BEGIN                                                  

            DECLARE cur_student CURSOR                     

                FOR SELECT name, class_id FROM  student;    

         END;                                                  

         $$                                                                           

         DELIMITER ;                                                                                                                         

 

在上面的示例中,光标的名称为cur_student;SELECT语句部分是从表student中查询出字段name和class_id的值。

2. 打开光标

在MySQL中,使用关键字OPEN来打开光标,其基本语法如下:

    OPEN cursor_name;

其中,参数cursor_name表示光标的名称。

下面代码打开一个名为cur_student的光标,代码如下:

    OPEN cur_student;

3. 使用光标

在MySQL中,使用关键字FETCH来使用光标,其基本语法如下:

    FETCH cursor_name

      INTO var_name[,var_name…];

其中,参数cursor_name表示光标的名称;参数var_name表示将光标中的SELECT语句查询出来的信息存入该参数中。var_name必须在声明光标之前就定义好。

【demo】下面声明一个名为cur_student的光标,代码如下:

mysql>  use school;   #选择数据库school                                                                                                                         

mysql> DELIMITER $$                                                                                

mysql> create procedure query_student (IN sid int, OUT cname varchar(128), OUT cid int)                                                                                    

        BEGIN                                                                             

            declare tmp_name varchar(128);    #必须定义在声明光标之前                                                                                             

            declare tmp_cid  int;                                                           

            declare  done int default 0;                                                                                                                                                

            declare cur_student CURSOR FOR SELECT name, class_id FROM  student where id = sid;                                                                                      

            declare continue handler for not found set done = 1; #将结束标志绑定到游标上                                                                             

            open  cur_student;                                                             

            select done;                                                                    

            fetch cur_student into tmp_name, tmp_cid;                                        

            select done;                                                                                      

            select tmp_name, tmp_cid;         #打印从光标中获取到的值                                                

            close cur_student;                                                              

            set cname = tmp_name, cid = tmp_cid;                                                                                                                      

         END;                                                                              

mysql>  $$                                                                                 

mysql>  DELIMITER ;                                                                                                                         

4. 关闭光标

在MySQL中,使用关键字CLOSE来关闭光标,其基本语法如下:

    CLOSE cursor_name;

其中,参数cursor_name表示光标的名称。

例如: 关闭一个名为cur_student的光标,代码如下:

    CLOSE cur_student;

在上面的示例中,关闭了这个名称为cur_student的光标。关闭了之后就不能使用FETCH来使用光标了。提示

如果存储过程或函数中执行了SELECT语句,并且SELECT语句会查询出多条记录,这种情况最好使用光标来逐条读取记录,光标必须在处理程序之前且在变量和条件之后声明,而且光标使用完毕后一定要关闭。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_44065088/article/details/107351389