Mysql create a stored procedure, use the cursor Cursor loop update

Use the cursor (cursor)


1. Declare the cursor


DECLARE cursor_name CURSOR FOR select_statement

This statement declares a cursor. The cursor may be defined in a plurality of subroutines, but in a block cursor for each must have a unique name. After declaring a cursor is a single operation, but can not use a SELECT statement can not have INTO clause.


2. OPEN cursor statement


OPEN cursor_name

This statement opens a previously declared cursor.


3. cursor FETCH statement


FETCH cursor_name INTO var_name [, var_name] ...

This statement with the specified open cursor reads the next line (the next line if there is any), and advances the cursor pointer.


4. Cursor CLOSE statement


CLOSE cursor_name

The statement closes a previously opened cursor.




Check before you write a lot of information but not always executed, after pondering for a moment from, wrote example, tested entirely correct.


The following is a stored procedure to create, using the example of a cursor loop update operation:


 

CREATE PROCEDURE `my`()

BEGIN

    / * Local variables defined DECLARE * /

  declare aid bigint default 0 ;

  declare mdsl bigint default 0;

  declare stop int default 0;

  declare cur CURSOR FOR (select  count(area_tb.id)  as mdsl, area_tb.id as aid from area_tb right join subbranch_tb on subbranch_tb.i_subbran_area=area_tb.id

where area_tb.i_record_status=0 and subbranch_tb.i_record_status=0 group by area_tb.id);

 

 declare CONTINUE HANDLER FOR SQLSTATE '02000' SET stop = null;

  / * Open the cursor * /

OPEN cur;

/ * Cursor to go one step down, two to check out the value paid two variables defined * /

FETCH cur INTO mdsl,aid;

/ * Loop that is clear of the cursor query the name will add up and use; separated number * /

WHILE ( stop is not null) DO

update area_tb set  i_subbran_count=mdsl where id = aid ;

/ * Take a step down cursor * /

FETCH cur INTO mdsl,aid;

END WHILE;

CLOSE cur;

END;


Finally, do not forget: to connect to the database user granted permission to execute a stored procedure


grant execute on procedure yunzuche.myupdate to 'username' @ '%';

Welcome to work one to five years of Java Java technology engineer friends to join exchange group: 659 270 626
provides free learning materials within the Java architecture group (which has high availability, high concurrency, high performance and distributed, Jvm performance tuning, Spring Source, MyBatis, more knowledge of Netty, Redis, Kafka, Mysql, Zookeeper, Tomcat, Docker, Dubbo, Nginx and big data infrastructure data) rational use of every minute of their own time to enhance their learning, do not reuse "no time" to hide his ideological laziness! Young, hard fight, give an account of their own future!

 


Guess you like

Origin blog.51cto.com/14028890/2422698
Recommended