An instance of using the MySql cursor

  • 2020-06-19 11:50:40
  • OfStack

The whole process of using the mysql cursor is:

1. Create cursors

DECLARE calc_bonus CURSOR FOR SELECT id, salary, commission FROM employees;

2. Open the cursor

OPEN calc_bonus;

3. Use cursors

FETCH calc_bonus INTO re_id, re_salary, re_comm;

4. Close the cursor

CLOSE calc_bonus;

The example code is as follows:


begin
declare temp_user_id int default null;
declare stop int default 0;
# Declare cursor 
 declare temp_cur cursor for select f_user_id from table_test where f_user_id=1;
 # Declare exception handling for cursors 
 declare continue handler for sqlstate '02000' set stop=1;
 open temp_cur;
 fetch temp_cur into temp_user_id;
 # Determines if the cursor has reached the end 
 while stop<>1 do
 # All kinds of judgment 
 # Read the 1 The data     
 fetch temp_cur into temp_user_id;   
 # End of the cycle    
 end while;  
 # Close the cursor  
 close temp_cur;
end


Related articles: