Pl/Sql_StoredProcedure_table 根据条件更新

Pl/Sql_StoredProcedure_table update based on condition

我编写了一个 plsql 过程,其中我想用表 2 中通过外键连接的相应值更新表 1 中的列 c1、c2。如果table2中不存在该行,那么我想将table1本身的c3的值设置为c2。在这种情况下,无需更新任何内容到 c1。你能帮我做一下吗?

CREATE OR REPLACE PROCEDURE update_table1
IS

BEGIN
  FOR t1_record IN (SELECT * FROM table1)
  LOOP
    IF t1_record.c2 is not null THEN
      UPDATE table1 x SET(c1, c2) = (SELECT y.id, y.name FROM table2 y WHERE y.id=t1_record.c2)
      WHERE x.id = t1_record.id AND EXISTS(SELECT 1 FROM table2 y WHERE y.id=t1_record.c2);

       -- Need to write else condition here for the inner if -----
    ElSIF 
       ---------------------
       -----------
    END IF;
  END LOOP;
END;

你说的方式和我理解问题的方式,你需要的不是 ELSIF,而是同一个 IF 中的另一个 UPDATE,但是这次 NOT EXISTS.

CREATE OR REPLACE PROCEDURE update_table1
IS
BEGIN
   FOR t1_record IN (SELECT * FROM table1)
   LOOP
      IF t1_record.c2 IS NOT NULL
      THEN
         UPDATE table1 x
            SET (c1, c2) =
                   (SELECT y.id, y.name
                      FROM table2 y
                     WHERE y.id = t1_record.c2)
          WHERE     x.id = t1_record.id
                AND EXISTS
                       (SELECT 1
                          FROM table2 y
                         WHERE y.id = t1_record.c2);

         UPDATE table1 x
            SET c3 = c2
          WHERE     x.id = t1_record.id
                AND NOT EXISTS
                       (SELECT 1
                          FROM table2 y
                         WHERE y.id = t1_record.c2);
      END IF;
   END LOOP;
END;

为什么循环?使用 merge 如下:

merge into table1 x
using (select x.id, x.c3, y.id, y.name 
        from table1 x left join tabl2 y
          on x.id = y.id) y
on (x.id = y.id)
when matched then
update set x.c1 = coalesce(y.id,x.c1), c2 = coalesce(y.name, x.c3);