Oracle 使用光标引用整个表,然后根据条件插入

Oracle 使用光标引用整个表,然后根据条件插入,oracle,if-statement,plsql,cursor,Oracle,If Statement,Plsql,Cursor,如果我使用光标引用整个表。我可以根据其他表中的条件多次使用insert语句吗?例如: V_Name Emp.Name%type; V_E_Number Emp.Number%type; V_Location Emp.Location%type; V_City Emp.City%type; V_P_ID Emp.P_ID%type; V_State_Cod

如果我使用光标引用整个表。我可以根据其他表中的条件多次使用insert语句吗?例如:

V_Name                 Emp.Name%type;
V_E_Number             Emp.Number%type;
V_Location             Emp.Location%type;
V_City                 Emp.City%type;
V_P_ID                 Emp.P_ID%type;
V_State_Code           Emp.State_Code%type;

Cursor C1 is Select emp.name, emp.number, emp.Location, emp.City, emp.P_ID, emp.State_Code
             From Employee Emp, Former_Employee Femp
             Where Emp.Number = Femp.Number
             And State_Code = '4';

Begin

Open C1;

Loop

Fetch C1 Into V_Name, V_E_Number, V_Location, V_City, V_P_ID, V_State_Code;

EXIT WHEN C1%NOTFOUND;

IF New_Emp.P_ID != V_P_ID 
Then Insert Into New_Emp
Values (V_Name, V_E_Number, V_Location, V_City, V_P_ID, V_State_Code); 

IF New_Emp.P_ID = V_P_ID,
   New_Emp.State_Code = V_State_Code
Then Insert Into Emp_Archive
VALUES (V_Name, V_E_Number, V_Location, V_City, V_P_ID, V_State_Code);  

Else Do Nothing;

End If;

End Loop;

Close C1;

End;
/ 

然后,我是否可以再次打开游标并使用另一条If语句以不同的条件填充不同的表?

您可以打开游标,从游标中提取,关闭游标,然后稍后重新打开它。再次打开光标时,可能会得到不同的数据,因为基础表中的数据可能已更改。但是,查看您的代码,似乎不需要首先声明游标——您只需编写两条
INSERT
语句(假设代码引用但未声明的
new\u emp
记录有效)

您可以通过执行一次“全部插入”来进一步简化该过程

INSERT ALL 
  WHEN new_emp.p_id = p_id
       THEN INTO new_emp( name, number, location, city, p_id, state_code )
              VALUES( name, number, location, city, p_id, state_code )
  WHEN new_emp.p_id = p_id AND
       new_emp.state_code = state_code
       THEN INTO emp_archive( name, number, location, city, p_id, state_code )
              VALUES( name, number, location, city, p_id, state_code )
  Select emp.name, emp.number, emp.Location, emp.City, emp.P_ID, emp.State_Code
    From Employee Emp, Former_Employee Femp
    Where Emp.Number = Femp.Number
      And State_Code = '4'  

听起来你自己能很好地回答这个问题。您尝试过吗?谢谢,我正在尝试学习pl/sql。你的回答很有帮助!
INSERT ALL 
  WHEN new_emp.p_id = p_id
       THEN INTO new_emp( name, number, location, city, p_id, state_code )
              VALUES( name, number, location, city, p_id, state_code )
  WHEN new_emp.p_id = p_id AND
       new_emp.state_code = state_code
       THEN INTO emp_archive( name, number, location, city, p_id, state_code )
              VALUES( name, number, location, city, p_id, state_code )
  Select emp.name, emp.number, emp.Location, emp.City, emp.P_ID, emp.State_Code
    From Employee Emp, Former_Employee Femp
    Where Emp.Number = Femp.Number
      And State_Code = '4'