简体   繁体   中英

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:

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 :

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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