标签:select code sel 记录 from nbsp family pre amp
cursor --------需要用户先定义,在select时,可以用于处理多行记录
1、declare 声明一个游标
2、open cursor (隐式游标自动open)
3、fetch cursor 读取记录到变量(在select时,可以通过循环的方式读取多行记录)
4、判断游标是否为空(到达最后一行记录)
5、close cusor 关闭游标
%isopen 判断游标是否open %found 判断游标是否为非空 %notfound 判断游标是否为空 %rowcount 在游标中处理的数据行数
①案例:通过显式游标select读取多行数据
SQL> declare
2 cursor cur_emp is
3 select * from emp where deptno=&no;
4
5 emp_rec emp%rowtype;
6
7 begin
8 if not cur_emp%isopen then
9 open cur_emp;
10 end if;
11
12 loop
13 fetch cur_emp into emp_rec ;
14 exit when cur_emp%notfound ;
15
16 dbms_output.put_line( emp_rec.ename ||‘ , ‘||emp_rec.sal||‘ , ‘|| emp_rec.deptno );
17 end loop;
18 close cur_emp;
19
20 end;
②通过for循环读取游标数据:
SQL> declare
2 cursor cur_emp is
3 select * from emp where deptno=&no;
4
5 begin
6 for emp_rec in cur_emp loop
7 dbms_output.put_line( emp_rec.ename ||‘ , ‘||emp_rec.sal||‘ , ‘|| emp_rec.deptno );
8 end loop;
9
10 end;
③带有参数的游标:通过参数传递给游标
SQL> declare
2
3 cursor emp_cur (v_deptno number) is
4 select * from emp where deptno=v_deptno;
5 emp_rec emp%rowtype;
6
7 begin
8 if not emp_cur%isopen then
9 open emp_cur(30);
10 end if;
11 loop
12 fetch emp_cur into emp_rec ;
13 exit when emp_cur%notfound;
14 dbms_output.put_line( emp_rec.ename ||‘ , ‘||emp_rec.sal||‘ , ‘|| emp_rec.deptno );
15 end loop;
16 end;
SQL> declare
2
3 cursor emp_cur (v_deptno number) is
4 select * from emp where deptno=v_deptno;
5 emp_rec emp%rowtype;
6
7 begin
8 if not emp_cur%isopen then
9 open emp_cur(20);
10 end if;
11 loop
12 fetch emp_cur into emp_rec ;
13 exit when emp_cur%notfound;
14 dbms_output.put_line( emp_rec.ename ||‘ , ‘||emp_rec.sal||‘ , ‘|| emp_rec.deptno );
15 end loop;
16 end;
④在for循环中嵌套游标(游标不需要declare)
SQL> begin
2 for emp_rec in (select * from emp where deptno=&no) loop
3 dbms_output.put_line( emp_rec.ename ||‘ , ‘||emp_rec.sal||‘ , ‘|| emp_rec.deptno );
4 end loop;
5
6 end;
标签:select code sel 记录 from nbsp family pre amp
原文地址:http://www.cnblogs.com/tomatoes-/p/6104386.html