oracle PL/SQL编程语言之游标的使用

(本文章内容仅在windows10下经测试能够运行,不能保证其他环境下的可靠性)

PL/SQL游标
概念:类似于集合

 

 

定义游标
关键字:cursor;
1、不带参数游标
语法:cursor 游标变量名 is 查询语句;

示例代码如下:

cursor c1 is select * from emp;

 


2、带参数游标
语法:cursor 游标变量名(参数名 数据类型...) is 查询语句(查询语句语句的右值可以使用游标参数);

示例代码如下:

cursor c2(dno emp.deptno%type) is select empno from emp where deptno = dno;

 

遍历游标

关键字:open;fetch;close; 

1、不带参数的游标

语法:

open 游标变量名;

  loop

    fetch 游标变量名 into 变量名;

    exit when 条件(常使用:游标变量名%notfound;)

    循环体(使用变量执行其他语句)

  end loop;

close 游标变量名;

示例代码如下:

open c1;
  loop
    fetch c1 into e;
    exit when c1%notfound;
    dbms_output.put_line(e.ename);
  end loop;
  close c1;

 

2、带参数的游标

语法:

open 游标变量名(实参列表);

 

  loop

    fetch 游标变量名 into 变量;

    exit loop 条件(常使用:游标变量名%notfound;)

    循环体(使用变量执行其他语句)

  end loop;

close 游标变量名;

示例代码如下:

open c2(10);
  loop
    fetch c2 into eno;
    exit when c2%notfound;
    update emp set sal = sal + 10 where empno = eno;
    commit;  
  end loop;
  close c2;

 

使用游标的两个简单案例

1、使用游标输出emp表所有员工姓名

示例代码如下:

--使用游标遍历输出emp表员工姓名
declare
  cursor c1 is select * from emp;
  e emp%rowtype;
begin
  open c1;
  loop
    fetch c1 into e;
    exit when c1%notfound;
    dbms_output.put_line(e.ename);
  end loop;
  close c1;
end;

 

2、使用游标给emp表部门编号为10的所有员工增加工资10

示例代码如下:

--使用游标给emp部门编号为10的员工涨10元工资
declare
  cursor c2(dno emp.deptno%type) is select empno from emp where deptno = dno;
  eno emp.empno%type;
begin
  open c2(10);
  loop
    fetch c2 into eno;
    exit when c2%notfound;
    update emp set sal = sal + 10 where empno = eno;
    commit;  
  end loop;
  close c2;
end;

 

posted @ 2020-06-06 12:06  DNoSay  阅读(393)  评论(0编辑  收藏  举报