--for 循环游标
declare
cursor my_cursor is select id,name,sex,age from t_user where rownum<10;
c_row my_cursor%rowtype;--游标行数据类型
begin
--c_row 完全可以直接用普通变量替代
for c_row in my_cursor loop
dbms_output.put_line(c_row.id||','||c_row.name||','||c_row.sex||','||c_row.age);
end loop;
end;
--fetch游标
--使用此游标必须明确的打开和关闭
declare
cursor my_cursor is select id,name,sex,age from t_user where rownum<20;
c_row my_cursor%rowtype;--游标行数据类型
begin
open my_cursor; --打开游标
loop
fetch my_cursor into c_row;
exit when my_cursor%notfound;
dbms_output.put_line(c_row.id||','||c_row.name||','||c_row.sex||','||c_row.age);
end loop;
end;
--fetch游标结合while
declare
cursor my_cursor is select id,name,sex,age from t_user where rownum<30;
c_row my_cursor%rowtype;--游标行数据类型
begin
open my_cursor; --打开游标
fetch my_cursor into c_row;
while my_cursor%found loop
dbms_output.put_line(c_row.id||','||c_row.name||','||c_row.sex||','||c_row.age);
fetch my_cursor into c_row;--继续获取下一行数据
end loop;
close my_cursor;
end;
--带参数的游标
declare
cursor my_cursor(p_area varchar2) is select id,name,sex,age from t_user where area=p_area;
c_row my_cursor%rowtype;--游标行数据类型
begin
for c_row in my_cursor('E017010') loop
dbms_output.put_line(c_row.id||','||c_row.name||','||c_row.sex||','||c_row.age);
end loop;
end;
--ref游标
declare
--type refcursor is ref cursor;--ref游标,弱类型
type refcursor is ref cursor return t_user%rowtype;--ref游标,强类型
user_cur refcursor;
c_row t_user%rowtype;
name t_user.name%type;
age t_user.age%type;
begin
open user_cur for select * from t_user where name like '王%' ;
loop
fetch user_cur into c_row;
exit when user_cur%notfound;
dbms_output.put_line(c_row.name||','||c_row.age);
end loop;
close user_cur;
end;