如何在 pl/sql 中更新 table?

How to update table in pl/sql?

为这个问题设计的例子。两个 table,项目和员工。员工有一个项目 ID 外键。查询需要

  1. select 2021 年在员工中处于持续状态的所有项目 table

  2. 对于上面的每条记录 select 语句 (1),

    • 在项目 table 中新建一行并将年份设置为 2022。

    • 获取项目 table 中新建行的项目 ID(第 3 步),并更新员工 table 中的所有外键(用新项目 ID 替换旧的对于每个相应的记录)

项目Table

id | name            | year | 
1  | alpha           | 2021 | 
2  | groundwork      | 2020 | 
3  | NETOS           | 2021 | 
5  | WebOPD          | 2019 | 

员工table

id | name  | year  | status     | project name     | projectID 
1  | john  | 2021  | ongoing    | alpha            | 1 
2  | linda | 2021  | completed  | NETOS            | 3 
3  | pat   | 2021  | WebOPD     | completed        | 5
4  | tom   | 2021  | ongoing    | alpha            | 1
insert into project with projects as 
(select max(id) over() max_p_id, id, name, year from project), temp as ( select distinct projectid, project_name from employee where status='ongoing') select max_p_id+row_number() over(order by p.id), p.name, 2022 from projects p join temp e on p.id=e.projectid where p.year=2021; 
declare
id_num project.project_id%type;
begin

/*for each loop u asked*/

for i in (select distinct p.name,p.project_id
from project p, employee e where p.name=e.project_name and 
p.year=to_date('2021','YYYY')
and e.status = 'ongoing') loop

/*here i made new unique id for project and saved it into id_num variable, you 
can use a sequence here it would be a better solution but I did it with a 
for loop*/

  for i in (select max(project_id) id_num from project)loop
    id_num:=i.id_num+1;
  end loop;

  /*inserting new project with same name, new date and new id*/

  insert into project values (id_num,i.name,to_date('2022','YYYY'));

  /*updating the employee table where is the old project_id*/

  update employee set employee.project_id=id_num where 
  employee.project_id=i.project_id; 
end loop;
end;

我已经对代码进行了注释,请务必阅读它,希望对您有所帮助。