欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

游标的使用

程序员文章站 2024-01-12 08:02:46
...
DECLARE cursor_name CURSOR FOR select_statement;
OPEN cursor_name;
FETCH cursor_name INTO var_name [, var_name] ...
CLOSE cursor_name
declare continue handler FOR SQLSTATE '02000' SET done = 1;  -- done变量需要先声明 declare done int;
示例1:
open cur_test;  
repeat  
    fetch cur_test into name, pass;  
    select concat_ws(',',result,name,pass) into result;  
until done end repeat;  
close cur_test; 

========嵌套游标或多次循环某个游标===========
declare done1 int;
delcare done2 int;
declare CONTINUE HANDLER for not found set done1 = 1;  
begin
delcare xxCur cursor for ...;
set done1=0;
open xxCur;
repeat1:repeat
  fetch xx into ...;
  if (done1=1) then
    leave repeat1;
  end if;
   begin
     declare xx2Cur cursor for ...;
      declare CONTINUE HANDLER for not found set done2 = 1;  
      set done2=0;
      open xx2Cur;
      repeat2:repeat
            fetch xx2 into ...;
            if (done2=1) then
                  leave repeat2;
            end if;
            ...
            
      until (done2=1) end repeat;
      close xx2Cur;
   end;
until (done1=1) end repeat;
close xxCur;
end;

通过视图(或临时表)实现动态游标

其实,可以在任意处用begin end把游标套起来就可以随时声明,尤其是嵌套游标的时候

declare cur_temp cursor for select v.* from view_temp_20150701 v;
set v_sql = 'create view view_temp_20150701 as select t.id from t_user t';
set @v_sql = v_sql;
prepare statement from @v_sql;
execute statement;
deallocate prepare statement;