2018.5.30 Oracle数据库PLSQL编程---游标的使用

/
显示游标处理步骤
1.声明游标
语法结构:cursor 游标名称 is SQL 语句;
2.打开游标
语法结构:open游标名称;
3.提取数据
语法结构:fetch
4.关闭游标
/

--显示员工表中的姓名(返回的是多条记录,必须使用游标来处理)

set serveroutput on;
declare
--变量
--1.声明游标
cursor c_emp is select ename,sal from emp;
v_ename emp.ename%type;
v_sal emp.sal%type;
begin
--代码块
--2.打开游标
open c_emp;
--使用loop循环
loop
--3.提取数据
fetch c_emp into v_ename,v_sal;
exit when c_emp%notfound; --判断游标是否还有数据
--输出信息
dbms_output.put_line('姓名:'||v_ename||',工资:'||v_sal);
end loop;

--4.关闭游标
close c_emp;
end;

--2.record类型实现
declare
cursor c_emp is select ename,sal from emp;
type type_emp is record(
v_ename emp.ename%type,
v_sal emp.sal%type
);

v_record type_emp;
begin
--代码块
--2.打开游标
open c_emp;
--使用loop循环
loop
--3.提取数据
fetch c_emp into v_record;
exit when c_emp%notfound; --判断游标是否还有数据
--输出信息
dbms_output.put_line('姓名:'||v_record.v_ename||',工资:'||v_record.v_sal);
end loop;
--4.关闭游标
close c_emp;
end;

--3.扩展:使用游标类型来转换
declare
cursor c_emp is select ename,sal,dname,loc from emp e,dept d where e.deptno=d.deptno;
v_cursor_emp c_emp%rowtype;

begin
--代码块
--2.打开游标
open c_emp;
--使用loop循环
loop
fetch c_emp into v_cursor_emp;
--3.提取数据
exit when c_emp%notfound; --判断游标是否还有数据
--输出信息
dbms_output.put_line('姓名:'||v_cursor_emp.ename||',工资:'||v_cursor_emp.sal || '部门名字:'||v_cursor_emp.dname);
end loop;

--4.关闭游标
close c_emp;
end;

--4.for(声明游标即可)
declare
cursor c_emp is select ename,sal,dname,loc from emp e,dept d where d.deptno=e.deptno;
begin
for i in c_emp loop
dbms_output.put_line('姓名:'||i.ename|| '工资:'||i.sal||'部门名称'||i.dname);
end loop;
end;

--5.带参数的游标
declare
cursor c_emp(v_deptno emp.deptno%type)is select ename,sal,dname,loc from emp e,dept d where d.deptno=e.deptno;
begin
for i in c_emp(&n) loop
dbms_output.put_line('姓名:'||i.ename|| '工资:'||i.sal||'部门名称'||i.dname||i.dname);
end loop;
end;

--6.触发器
create or replace trigger t_1
after
insert on emp
begin
dbms_output.put_line('数据已经插入');
end;

insert into emp(empno,ename) values(11,'Legend');

猜你喜欢

转载自www.cnblogs.com/qichunlin/p/9102458.html