Search code examples
oracle-databaseplsqloracle11gplsqldeveloper

I want to update table emp_appointment with data from other table data


I have two tables named emp_appointment and employees. Employees have 2 column named EMPLOYEE_ID1 and SUBSID_ACCOUNT_IDX and table emp_appointment have also 2 column named dep_id and EMPLOYEE_ID1 I want to update table emp_appointment column dep_id with data of employees table from column SUBSID_ACCOUNT_IDX both have same id's so I write this code but not worked

DECLARE  
   EMP_id EMPLOYEES.EMPLOYEE_ID1%TYPE;  
   SUBSID_ID EMPLOYEES.SUBSID_ACCOUNT_IDX%TYPE;
 
   CURSOR C_EMP is  
      SELECT EMPLOYEE_ID1, SUBSID_ACCOUNT_IDX FROM EMPLOYEES WHERE SUBSID_ACCOUNT_IDX =  EMPLOYEE_ID1 ;  
BEGIN  
   OPEN C_EMP;  
   LOOP  
      FETCH C_EMP into EMP_id,SUBSID_ID ;
      UPDATE EMP_APPOINTMENT
  SET DEP_ID = SUBSID_ID
WHERE EMPLOYEE_ID1= SUBSID_ID; 
      EXIT WHEN C_EMP%notfound;      
      
END LOOP;  
CLOSE C_EMP;  
END;

help needed from Masters Please


Solution

  • First off you should not do this, unless dep_id id necessary as part of a foreign key. What you are doing is just copying data, which is just a bad idea. It exposes you to data inconsistency, what happens when dep_id contains a value that does not exist in employees. Instead you should just Join the tables and select subsid_account_idx from employees. But if you insistant then just use a single update.

    update emp_appointment  ea 
        set dep_id = (select subsid_account_idx 
                        from employees e 
                       where e.employee_id1 = ea.employee_id1
                     );