MySQL cursor syntax instance bitsCN.com
MySQL cursor syntax instance
1. basic syntax:
SQL code
# Define a cursor
Declare fetchSeqCursor cursor for select seqname, value from sys_sequence;
# Use a cursor
Open fetchSeqCursor;
# Fetch data
Fetch cursor into _ seqname, _ value;
# Closing a cursor
Close fetchSeqCursor;
2. single cursor example:
SQL code
# Define the flag for loop judgement
Declare fetchSeqOk boolean;
# Define the varient for store the data
Declare _ seqname varchar (50 );
Declare _ value bigint (20 );
# Define the cursor
Declare fetchSeqCursor cursor for select seqname, value from sys_sequence;
# Define the continue handler for not found flag
Declare continue handler for not found set fetchSeqOk = true;
Set fetchSeqOk = false;
Open fetchSeqCursor;
FetchSeqLoop: Loop
If fetchSeqOk then
Leave fetchSeqLoop;
Else
Fetch cursor into _ seqname, _ value;
Select _ seqname, _ value;
End if;
End Loop;
Close fetchSeqCursor;
3. nested cursor loop
Java code
# Define the flag for loop judgement
Declare fetchSeqOk boolean;
# Define the varient for store the data
Declare _ seqname varchar (50 );
Declare _ value bigint (20 );
# Define the cursor
Declare fetchSeqCursor cursor for select seqname, value from sys_sequence;
# Define the continue handler for not found flag
Declare continue handler for not found set fetchSeqOk = true;
Set fetchSeqOk = false;
Open fetchSeqCursor;
FetchSeqLoop: Loop
If fetchSeqOk then
Leave fetchSeqLoop;
Else
Fetch cursor into _ seqname, _ value;
# Nested cursor loop
Begin
Declare fetchSeqOk boolean default 'inner ';
# Define the cursor
Declare cursor2 cursor for select... from ...;
# Define the continue handler for not
Declare continue handler for not found set fetchSeqOk = true;
Set fetchSeqOk = false;
Open cursor2;
Fetchloop2 loop
If fetchSeqOk then
Else
End if;
End loop;
Close cursor2;
End;
# Nested cursor loop ends
End if;
End Loop;
Close fetchSeqCursor;
BitsCN.com