---
title: "Oracle--游标"
author: "keepwork"
date: "2013-12-23T21:13:12Z"
tags: []
categories: ["数据库"]
slug: "oracle"
draft: false
lastmod: "2014-04-06T23:42:35Z"
id: 1994111
url: "https://keepwork.iteye.com/blog/1994111"
---

**开发者博客：[www.developsearch.com](http://www.developsearch.com "开发者博客")**

 

-- 声明游标；CURSOR cursor\_name IS select\_statement

 

--For 循环游标

--（1）定义游标

--（2）定义游标变量

--（3）使用for循环来使用这个游标

declare

       --类型定义

       cursor c\_job

       is

       select empno,ename,job,sal

       from emp

       where job='MANAGER';

       --定义一个游标变量v\_cinfo c\_emp%ROWTYPE ，该类型为游标c\_emp中的一行数据类型

       c\_row c\_job%rowtype;

begin

       for c\_row in c\_job loop

         dbms\_output.put\_line(c\_row.empno||'-'||c\_row.ename||'-'||c\_row.job||'-'||c\_row.sal);

       end loop;

end;

 

 

     

--Fetch游标

--使用的时候必须要明确的打开和关闭

 

declare

       --类型定义

       cursor c\_job

       is

       select empno,ename,job,sal

       from emp

       where job='MANAGER';

       --定义一个游标变量

       c\_row c\_job%rowtype;

begin

       open c\_job;

         loop

           --提取一行数据到c\_row

           fetch c\_job into c\_row;

           --判读是否提取到值，没取到值就退出

           --取到值c\_job%notfound 是false

           --取不到值c\_job%notfound 是true

           exit when c\_job%notfound;

            dbms\_output.put\_line(c\_row.empno||'-'||c\_row.ename||'-'||c\_row.job||'-'||c\_row.sal);

         end loop;

       --关闭游标

      close c\_job;

end;

 

--1：任意执行一个update操作，用隐式游标sql的属性%found,%notfound,%rowcount,%isopen观察update语句的执行情况。

       begin

         update emp set ENAME='ALEARK' WHERE EMPNO=7469;

         if sql%isopen then

           dbms\_output.put\_line('Openging');

           else

             dbms\_output.put\_line('closing');

             end if;

          if sql%found then

            dbms\_output.put\_line('游标指向了有效行');--判断游标是否指向有效行

            else

              dbms\_output.put\_line('Sorry');

              end if;

              if sql%notfound then

                dbms\_output.put\_line('Also Sorry');

                else

                  dbms\_output.put\_line('Haha');

                  end if;

                   dbms\_output.put\_line(sql%rowcount);

                   exception

                     when no\_data\_found then

                       dbms\_output.put\_line('Sorry No data');

                       when too\_many\_rows then

                         dbms\_output.put\_line('Too Many rows');

                         end;

declare

       empNumber emp.EMPNO%TYPE;

       empName emp.ENAME%TYPE;

       begin

         if sql%isopen then

           dbms\_output.put\_line('Cursor is opinging');

           else

             dbms\_output.put\_line('Cursor is Close');

             end if;

             if sql%notfound then

               dbms\_output.put\_line('No Value');

               else

                 dbms\_output.put\_line(empNumber);

                 end if;

                 dbms\_output.put\_line(sql%rowcount);

                 dbms\_output.put\_line('-------------');

                

                 select EMPNO,ENAME into  empNumber,empName from emp where EMPNO=7499;

                 dbms\_output.put\_line(sql%rowcount);

                

                if sql%isopen then

                dbms\_output.put\_line('Cursor is opinging');

                else

                dbms\_output.put\_line('Cursor is Closing');

                end if;

                 if sql%notfound then

                 dbms\_output.put\_line('No Value');

                 else

                 dbms\_output.put\_line(empNumber);

                 end if;

                 exception

                   when no\_data\_found then

                     dbms\_output.put\_line('No Value');

                     when too\_many\_rows then

                       dbms\_output.put\_line('too many rows');

                       end;

                  

                

      

--2,使用游标和loop循环来显示所有部门的名称

--游标声明

declare

       cursor csr\_dept

       is

       --select语句

       select DNAME

       from Depth;

       --指定行指针,这句话应该是指定和csr\_dept行类型相同的变量

       row\_dept csr\_dept%rowtype;

begin

       --for循环

       for row\_dept in csr\_dept loop

           dbms\_output.put\_line('部门名称:'||row\_dept.DNAME);

       end loop;

end;

 

 

--3,使用游标和while循环来显示所有部门的的地理位置（用%found属性）

declare

       --游标声明

       cursor csr\_TestWhile

       is

       --select语句

       select  LOC

       from Depth;

       --指定行指针

       row\_loc csr\_TestWhile%rowtype;

begin

  --打开游标

       open csr\_TestWhile;

       --给第一行喂数据

       fetch csr\_TestWhile into row\_loc;

       --测试是否有数据，并执行循环

         while csr\_TestWhile%found loop

           dbms\_output.put\_line('部门地点：'||row\_loc.LOC);

           --给下一行喂数据

           fetch csr\_TestWhile into row\_loc;

         end loop;

       close csr\_TestWhile;

end;

select * from emp

 

 

 

      

--4,接收用户输入的部门编号，用for循环和游标，打印出此部门的所有雇员的所有信息(使用循环游标)

--CURSOR cursor\_name\[(parameter\[,parameter],...)] IS select\_statement;

--定义参数的语法如下:Parameter\_name \[IN] data\_type\[{:=|DEFAULT} value] 

 

declare

      CURSOR

      c\_dept(p\_deptNo number)

      is

      select * from emp where emp.depno=p\_deptNo;

      r\_emp emp%rowtype;

begin

        for r\_emp in c\_dept(20) loop

            dbms\_output.put\_line('员工号：'||r\_emp.EMPNO||'员工名：'||r\_emp.ENAME||'工资：'||r\_emp.SAL);

        end loop;

end;

select * from emp  

--5：向游标传递一个工种，显示此工种的所有雇员的所有信息(使用参数游标)

declare

       cursor

       c\_job(p\_job nvarchar2)

       is

       select * from emp where JOB=p\_job;

       r\_job emp%rowtype;

begin

       for r\_job in c\_job('CLERK') loop

           dbms\_output.put\_line('员工号'||r\_job.EMPNO||' '||'员工姓名'||r\_job.ENAME);

        end loop;

end;

SELECT * FROM EMP

 

--6：用更新游标来为雇员加佣金：(用if实现,创建一个与emp表一摸一样的emp1表，对emp1表进行修改操作),并将更新前后的数据输出出来

--[http://zheng12tian.iteye.com/blog/815770](http://zheng12tian.iteye.com/blog/815770)

        create table emp1 as select * from emp;

       

declare

        cursor

        csr\_Update

        is

        select * from  emp1 for update OF SAL;

        empInfo csr\_Update%rowtype;

        saleInfo  emp1.SAL%TYPE;

begin

    FOR empInfo IN csr\_Update LOOP

      IF empInfo.SAL&lt;1500 THEN

        saleInfo:=empInfo.SAL\*1.2;

       elsif empInfo.SAL&lt;2000 THEN

        saleInfo:=empInfo.SAL\*1.5;

        elsif empInfo.SAL&lt;3000 THEN

        saleInfo:=empInfo.SAL\*2;

      END IF;

      UPDATE emp1 SET SAL=saleInfo WHERE CURRENT OF csr\_Update;

     END LOOP;

END;

 

--7:编写一个PL/SQL程序块，对名字以‘A’或‘S’开始的所有雇员按他们的基本薪水(sal)的10%给他们加薪(对emp1表进行修改操作)

declare

     cursor

      csr\_AddSal

     is

      select * from emp1 where ENAME LIKE 'A%' OR ENAME LIKE 'S%' for update OF SAL;

      r\_AddSal csr\_AddSal%rowtype;

      saleInfo  emp1.SAL%TYPE;

begin

      for r\_AddSal in csr\_AddSal loop

          dbms\_output.put\_line(r\_AddSal.ENAME||'原来的工资:'||r\_AddSal.SAL);

          saleInfo:=r\_AddSal.SAL\*1.1;

          UPDATE emp1 SET SAL=saleInfo WHERE CURRENT OF csr\_AddSal;

      end loop;

end;

--8：编写一个PL/SQL程序块，对所有的salesman增加佣金(comm)500

declare

      cursor

          csr\_AddComm(p\_job nvarchar2)

      is

          select * from emp1 where   JOB=p\_job FOR UPDATE OF COMM;

      r\_AddComm  emp1%rowtype;

      commInfo emp1.comm%type;

begin

    for r\_AddComm in csr\_AddComm('SALESMAN') LOOP

        commInfo:=r\_AddComm.COMM+500;

         UPDATE EMP1 SET COMM=commInfo where CURRENT OF csr\_AddComm;

    END LOOP;

END;

 

--9：编写一个PL/SQL程序块，以提升2个资格最老的职员为MANAGER（工作时间越长，资格越老）

--（提示：可以定义一个变量作为计数器控制游标只提取两条数据；也可以在声明游标的时候把雇员中资格最老的两个人查出来放到游标中。）

declare

    cursor crs\_testComput

    is

    select * from emp1 order by HIREDATE asc;

    --计数器

    top\_two number:=2;

    r\_testComput crs\_testComput%rowtype;

begin

    open crs\_testComput;

       FETCH crs\_testComput INTO r\_testComput;

          while top\_two&gt;0 loop

             dbms\_output.put\_line('员工姓名：'||r\_testComput.ENAME||' 工作时间：'||r\_testComput.HIREDATE);

             --计速器减一

             top\_two:=top\_two-1;

             FETCH crs\_testComput INTO r\_testComput;

           end loop;

     close crs\_testComput;

end;

   

 

--10：编写一个PL/SQL程序块，对所有雇员按他们的基本薪水(sal)的20%为他们加薪，

--如果增加的薪水大于300就取消加薪(对emp1表进行修改操作，并将更新前后的数据输出出来)

declare

    cursor

        crs\_UpadateSal

    is

        select * from emp1 for update of SAL;

        r\_UpdateSal crs\_UpadateSal%rowtype;

        salAdd emp1.sal%type;

        salInfo emp1.sal%type;

begin

        for r\_UpdateSal in crs\_UpadateSal loop

           salAdd:= r\_UpdateSal.SAL\*0.2;

           if salAdd&gt;300 then

             salInfo:=r\_UpdateSal.SAL;

              dbms\_output.put\_line(r\_UpdateSal.ENAME||':  加薪失败。'||'薪水维持在：'||r\_UpdateSal.SAL);

             else

              salInfo:=r\_UpdateSal.SAL+salAdd;

              dbms\_output.put\_line(r\_UpdateSal.ENAME||':  加薪成功.'||'薪水变为：'||salInfo);

           end if;

           update emp1 set SAL=salInfo where current of crs\_UpadateSal;

        end loop;

end;

    

--11:将每位员工工作了多少年零多少月零多少天输出出来  

--近似

  --CEIL(n)函数：取大于等于数值n的最小整数

  --FLOOR(n)函数：取小于等于数值n的最大整数

  --truc的用法 [http://publish.it168.com/2005/1028/20051028034101.shtml](http://publish.it168.com/2005/1028/20051028034101.shtml)

declare

  cursor

   crs\_WorkDay

   is

   select ENAME,HIREDATE, trunc(months\_between(sysdate, hiredate) / 12) AS SPANDYEARS,

       trunc(mod(months\_between(sysdate, hiredate), 12)) AS months,

       trunc(mod(mod(sysdate - hiredate, 365), 12)) as days

   from emp1;

  r\_WorkDay crs\_WorkDay%rowtype;

begin

    for   r\_WorkDay in crs\_WorkDay loop

    dbms\_output.put\_line(r\_WorkDay.ENAME||'已经工作了'||r\_WorkDay.SPANDYEARS||'年,零'||r\_WorkDay.months||'月,零'||r\_WorkDay.days||'天');

    end loop;

end;

 

--12:输入部门编号，按照下列加薪比例执行(用CASE实现，创建一个emp1表，修改emp1表的数据),并将更新前后的数据输出出来

--  deptno  raise(%)

--  10      5%

--  20      10%

--  30      15%

--  40      20%

--  加薪比例以现有的sal为标准

--CASE expr WHEN comparison\_expr THEN return\_expr

--\[, WHEN comparison\_expr THEN return\_expr]... \[ELSE else\_expr] END

declare

     cursor

         crs\_caseTest

          is

          select * from emp1 for update of SAL;

          r\_caseTest crs\_caseTest%rowtype;

          salInfo emp1.sal%type;

     begin

         for r\_caseTest in crs\_caseTest loop

         case

           when r\_caseTest.DEPNO=10

           THEN salInfo:=r\_caseTest.SAL\*1.05;

           when r\_caseTest.DEPNO=20

           THEN salInfo:=r\_caseTest.SAL\*1.1;

           when r\_caseTest.DEPNO=30

           THEN salInfo:=r\_caseTest.SAL\*1.15;

            when r\_caseTest.DEPNO=40

           THEN salInfo:=r\_caseTest.SAL\*1.2;

         end case;

          update emp1 set SAL=salInfo where current of crs\_caseTest;

        end loop;

end;

 

--13:对每位员工的薪水进行判断，如果该员工薪水高于其所在部门的平均薪水，则将其薪水减50元，输出更新前后的薪水，员工姓名，所在部门编号。

--AVG(\[distinct|all] expr) over (analytic\_clause)

---作用：

--按照analytic\_clause中的规则求分组平均值。

  --分析函数语法:

  --FUNCTION\_NAME(&lt;argument&gt;,&lt;argument&gt;...)

  --OVER

  --(&lt;Partition-Clause&gt;&lt;Order-by-Clause&gt;&lt;Windowing Clause&gt;)

     --PARTITION子句

     --按照表达式分区(就是分组),如果省略了分区子句,则全部的结果集被看作是一个单一的组

     select * from emp1

DECLARE

     CURSOR

     crs\_testAvg

     IS

     select EMPNO,ENAME,JOB,SAL,DEPNO,AVG(SAL) OVER (PARTITION BY DEPNO ) AS DEP\_AVG

     FROM EMP1 for update of SAL;

     r\_testAvg crs\_testAvg%rowtype;

     salInfo emp1.sal%type;

     begin

     for r\_testAvg in crs\_testAvg loop

     if r\_testAvg.SAL&gt;r\_testAvg.DEP\_AVG then

     salInfo:=r\_testAvg.SAL-50;

     end if;

     update emp1 set SAL=salInfo where current of crs\_testAvg;

     end loop;

end;

 

**开发者博客：[www.developsearch.com](http://www.developsearch.com "开发者博客")**