专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

Oracle 静态游标 oracle 静态游标和动态游标

ins518 2024-10-14 12:45:43 技术文章 19 ℃ 0 评论

游标: *****

游标类似于一个箭头,以行为单位,从上往下的对行数据进行读取的一个数据库的虚拟的对象。


1. 静态游标

-- 声明一个游标,让这个游标去读取某个select查询语句的结果

cursor 游标名字 is select查询语句;


-- 打开这个游标,启动它

open 游标名字;


-- 让游标往下移动一行,获取游标当前所在行查询到的数据

fetch 游标名字 into 变量名字;


-- 关闭和结束这个游标

close 游标名字;


使用while循环操作游标的方法:

declare

-- 声明一个游标,让这个游标去读取某个select查询语句的结果

cursor m is select * from emp where deptno=10;

-- 准备一个记录型变量存储表格的数据

u emp%rowtype;

begin

-- 打开这个游标,启动它

open m;

-- 获取游标当前所在行查询到的数据

fetch m into u;

-- 添加循环,将查询的结果全部打印出来

while m%found loop

dbms_output.put_line(u.ename);

fetch m into u;

end loop;

-- 关闭和结束这个游标

close m;

end;


使用loop操作循环的方法:

declare

cursor m is select * from emp where deptno=20;

u emp%rowtype;

begin

open m;

loop

fetch m into u;

exit when m%notfound;

dbms_output.put_line(u.ename);

end loop;

close m;

end;


使用for循环操作游标:

declare

cursor m is select * from emp where deptno=30;

begin

for i in m loop

dbms_output.put_line(i.ename);

end loop;

end;


declare

begin

for i in (select * from emp where deptno=30) loop

dbms_output.put_line(i.ename);

end loop;

end;


面试题:

-- 有一个表格结构如下,使用代码块批量的插入100-200的所有的数字

create table s23(

n number

);

declare

begin

for i in 100..200 loop

insert into s23 values(i);

commit;

end loop;

end;

select * from s23;


-- 使用游标,将这个表格里面,两两相加等于288的数字,成对的打印出来

declare

begin

for i in (select n from s23) loop

for j in (select n from s23) loop

if i.n+j.n=288 and i.n<j.n then

dbms_output.put_line(i.n||','||j.n);

end if;

end loop;

end loop;

end;

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表