简体   繁体   English

oracle db更新if条件

[英]oracle db update on if condition

i have created two tables and want to update the rows of one table with values from the other one. 我已经创建了两个表,并想用另一个表的值更新一个表的行。 But there are some conditions that must be met. 但是,必须满足一些条件。 I've tried it by the following example, but it didn't work. 我已经通过以下示例进行了尝试,但是没有用。

    BEGIN
    SELECT * FROM table_1, table_2;
    IF table_1.column_2 = table_2.column_2 AND table_1.column_1 IS NULL THEN    
        UPDATE table_1 SET table_1.column_1 = table_2.column_1;
    ELSIF ((table_1.column_2 = table_2.column_2) AND table_1.column_3 IS NULL) THEN
        UPDATE table_1 SET table_1.column_3 = table_2.column_3;
    ELSIF ((table_1.column_2 = table_2.column_2) AND (table_1.column_3 IS NULL) 
              AND (table_1.column_1 IS NULL)) THEN
        UPDATE table_1 SET table_1.column_3 = table_2.column_3, table_1.column_2 = table_2.column_2;
    ELSE
        INSERT INTO table_1 (column_2, column_1, column_3) 
        VALUES (table_2.column_2, table_2.column_1, table_2.column_3);
    END IF;
END;
/

Has someone a hint for me? 有人给我提示吗?

You just have to work a bit further to be able to loop on your result lines: 您只需要进一步工作,就可以循环显示结果行:

begin
  for line in
  (
    SELECT t1.column_1 c11, t1.column_2 c12, t1.column_3 c13,
           t2.column_1 c21, t2.column_2 c22, t2.column_3 c23
    FROM table_1 t1, table_2 t2
  )
  loop
    IF line.c12 = line.c22 AND line.c11 IS NULL THEN    
        UPDATE table_1 SET column_1 = line.c21;
    ELSIF ((line.c12 = line.c22) AND line.c13 IS NULL) THEN
        UPDATE table_1 SET column_3 = line.c23;
    ELSIF ((line.c12 = line.c22) AND (line.c13 IS NULL) 
              AND (line.c11 IS NULL)) THEN
        UPDATE table_1 SET column_3 = line.c23, column_2 = line.c22;
    ELSE
        INSERT INTO table_1 (column_2, column_1, column_3) 
        VALUES (line.c22, line.c21, line.c23);
    END IF;

  end loop;
end;
/

Hi you need to use a cursor to fetch each row then compare and update, here's how to use a cursor in oracle: 嗨,您需要使用游标读取每一行,然后进行比较和更新,以下是在oracle中使用游标的方法:

DECLARE
  CURSOR c1 IS
    SELECT last_name, job_id FROM employees
    WHERE manager_id > 120
    ORDER BY last_name;
BEGIN
  FOR item IN c1
  LOOP
       //do your stuff with item.field
  END LOOP;
END;

As @Polppan commented, this is best done with MERGE : 正如@Polppan所说,最好使用MERGE完成:

MERGE INTO table_1 
USING      table_2
   ON (table_1.column_2 = table_2.column_2)
 WHEN MATCHED THEN UPDATE SET 
      table_1.column_1 = table_2.column_2,
      table_1.column_3 = table_2.column_3
 WHEN NOT MATCHED THEN 
      INSERT (column_1, column_2, column_3)
      VALUES (table_2.column_1, table_2.column_2, table_2.column_3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM