如何更新 Employee table 中 Salary Column 的所有行?下面是我的代码

How to update all rows from Salary Column in Employee table?Below is my code

我想使用 PL/SQL oracle 更新所有员工的薪水。这是我的代码。

DECLARE 
           c_id customers.id%type; 
           c_sal  customers.salary%type; 
        BEGIN 
       SELECT  salary  
       INTO  c_sal 
       FROM customers; 

       IF (c_sal <= 6500) THEN 
          UPDATE customers  
          SET salary =  salary + 1000;


          dbms_output.put_line ('Salary updated'); 
       END IF; 

    END; 
    /

这是员工 Table:

select * 来自客户;

ID  NAME     AGE    ADDRESS                     SALARY
1   Ramesh   32     Ahmedabad                   3000
2   Khilan   25     Delhi                       1500
3   kaushik  23     Kota                        2000
4   Chaitali 25     Mumbai                      6500
5   Hardik   27     Bhopal                      8500
6   Komal    22     MP                          4500

根据您的问题,您想要更新 all the rows in Employee table 具有 salary <= 6500。所以你不需要任何变量或 select 查询。您可以在您的过程中有一个简单的更新语句。不需要 DECLARE 部分。

BEGIN 
 UPDATE customers  
 SET salary = salary + 1000
 WHERE salary <= 6500;
 COMMIT;
 dbms_output.put_line ('Salary updated');

 EXCEPTION
  WHEN NO_DATA_FOUND THEN
   dbms_output.put_line ('No any employee is having Salary <= 6500.');
END; 
/

如你所愿IF-ELSE,你可以用光标来实现。但是,我将始终选择上面显示的第一个选项。下面是使用 IF-ELSE:

的光标代码
DECLARE 
  CURSOR my_cursor IS select * FROM customers;
BEGIN
  FOR r1 in c1
   LOOP
     IF (r1.salary <= 6500) THEN
      UPDATE customers c SET c.salary = (c.salary + 1000) WHERE c.id = r1.id;
      -- If id is not primary/unique key, use WHERE CURRENT OF c1
     END IF;
     COMMIT;
   END LOOP;
END; 
/
DECLARE
c_id customers.id%type := 1; 
c_sal  customers.salary%type; 
        BEGIN 
       SELECT  salary  
   INTO  c_sal 
   FROM customers 
   where id=c_id;
   IF (c_sal <= 6500) THEN 
      UPDATE customers  
      SET salary =  salary + 1000;
      dbms_output.put_line ('Salary updated'); 
   END IF; 

END; 
/