使用for循环在oracle sql中更新多行

时间:2014-01-28 12:16:56

标签: sql oracle plsql

以下FOR循环不起作用。我在表t1和表t2中有两列PID,PAYMENT。我想从表t2更新表t1中的PAYMENT,其中t1.PID = t2.PID

FOR X  IN(select paymentterm,pid from temp_project)  
LOOP
  update project p
set p.paymentterm=temp_project.PID
where p.PID=X.PID;
END LOOP;
commit;

2 个答案:

答案 0 :(得分:3)

您可以在不循环的情况下实现此行为:

UPDATE project
SET    paymentterm = (SELECT peymentterm
                      FROM   temp_project
                      WHERE  project.pid = temp_project.pid)
WHERE  pid IN (SELECT pid FROM temp_project)

答案 1 :(得分:2)

尝试:

update project p
set    paymentterm = (select t.paymentterm
                        from temp_project tp
                       where tp.pid = p.pid)
where  pid in (select pid from temp_project)

...或者,如果temp_project.pid被限制为唯一:

update (select p.pid,
               p.paymentterm,
               t.paymentterm new_paymentterm
          from project p join temp_project t on p.pid = t.pid)
set    paymentterm = new_paymentterm;

您可以确保在以下情况下不进行更改:

update (select p.pid,
               p.paymentterm,
               t.paymentterm new_paymentterm
          from project p join temp_project t on p.pid = t.pid
         where coalesce(p.paymentterm,-1000) != coalesce(t.paymentterm,-1000))
set    paymentterm = new_paymentterm;

(猜测-1000对于那里的payterm来说是不可能的值)。 这也可以写成MERGE语句。