Oracle数据库中游标的使用
游标的定义:游标的作用在前面的文章中有提到过,查询结果如果超过一行,就需要使用游标。在文章”Oracle数据中的PL/SQL介绍“。创建步骤:定义一个游标语法:CURSOR cursor_name is select _statement;打开游标语法:open cursor_name;提取数据使用fetch,fetch关键字会抓取当前行的记录,并将记录指针下移一行。就像JdbC中的ResultSet一样。语法:fetch cursor_name into variable1,variable2.游标的一些属性关闭游标语法:close cursor_name示例代码如下:普通的方法:
--含有条件的游标--实现目标是,查询每个班的学生declare--先要定义两个游标--定义tab_class游标cursor s_tab_class isselect * from tab_class;--定义tab_stu游标,但是这里需要一个参数,就是班级的idcursor s_tab_stu(v_class_id number) isselect * from tab_stu where class_id=v_class_id;--定义两个存储变量--定义tab_classv_tab_class_rowtype tab_class%rowtype;--定义tab_stuv_tab_stu_rowtype tab_stu%rowtype;begin --打开游标 open s_tab_class; loop --提取数据 fetch s_tab_class into v_tab_class_rowtype; exit when s_tab_class%notfound; dbms_output.put_line('班级:'||v_tab_class_rowtype.class_name||'含有'); --嵌套循环,遍历当前班级的学生 open s_tab_stu(v_tab_class_rowtype.class_id); loop fetch s_tab_stu into v_tab_stu_rowtype; exit when s_tab_stu%notfound; dbms_output.put_line(v_tab_stu_rowtype.stu_name); end loop; close s_tab_stu; end loop; close s_tab_class;end;