Oracle中用游标更新字段值的面试题

如下表

SQL> set pagesize 60;
SQL> run;
  1* select * from employee

NAME           SALARY
---------- ----------
SMITH             800
ALLEN            1600
WARD             1250
JONES            2975
MARTIN           1250
BLAKE            2850
CLARK            2450
SCOTT            3000
KING             5000
TURNER           1500
ADAMS            1100
JAMES             950
FORD             3000
MILLER           1300

已选择14行。


在这个表如果SALARY列小于2500 就加20%。这个很简单,但是要用把游标用进去就要如下思考了:

先建个游标,遍历这个表在这个条件的数据。

 

SQL>  create or replace procedure emp_test
  2  is
  3   v_name employee.name%type;
  4   v_sal employee.salary%type;
  5   cursor cursor_sal is
  6   select name,salary from employee where salary<2500;
  7   begin
  8   open cursor_sal ;
  9   loop
 10   fetch cursor_sal into v_name,v_sal;
 11   exit when cursor_sal%notfound;
 12   update employee set salary=salary*1.2 where name=v_name;
 13   end loop;
 14   close cursor_sal;
 15   end;
 16   /

过程已创建。
SQL> set serveroutput on ;
SQL> exec emp_test;

PL/SQL 过程已成功完成。

SQL> select * from employee;

NAME           SALARY
---------- ----------
SMITH          1382.4
ALLEN            1920
WARD             1500
JONES            2975
MARTIN           1500
BLAKE            2850
CLARK            2940
SCOTT            3000
KING             5000
TURNER           1800
ADAMS            1320
JAMES            1368
FORD             3000
MILLER           1560

已选择14行。



 

你可能感兴趣的:(Oracle中用游标更新字段值的面试题)