简体   繁体   中英

Oracle SQL-Updating Rows with Another Table Key

I am using SQL developer

I am writing code to update several columns.

I have many ID column in two tables and department columns.

I want to change table 1 columns value.

update table1 a
set a.key_ıd = (case 
                   when a.key_ıd = 1 then 101
                   when a.key_ıd = 2 then 102
                   .
                   .
                   else a.ıd 
                end)
from table1 a, table2 b
where a.ıd = b.ıd
  and b.key_ıd in (1, 2, ...)
  and b.type <> 2;

But from line getting red, any suggestions?

Error at Command Line: 5 Column: 1
Error report -
SQL Error: ORA-00933:
00933. 00000 - "SQL command not properly ended"
*Cause:
*Action:

I don't understand why this code doesn't work.

Thanks.

I think you want exists :

UPDATE table1 a
    SET a.key_ıd = (CASE WHEN a.key_ıd=1 THEN 101
                         WHEN a.key_ıd=2 THEN 102
                                       .
                                       .
                         ELSE a.ıd
                    END)
    WHERE EXISTS (SELECT 1
                  FROM table2 b
                  WHERE a.ıd = b.ıd AND
                        b.key_ıd IN (1,2,...) AND
                        b.type <> 2
                  );

Oracle doesn't support a FROM clause in UPDATE . And the logic for setting the new values only uses the table being updated. So, you just want to filter the rows that are affected. For this EXISTS is a suitable approach.

One option would be using a MERGE Statement with WHEN MATCHED option such as

MERGE INTO table1 t1
USING ( SELECT *
          FROM table2 t ) t2
   ON ( t1.id = t2.id AND t2.type <> 2 AND t2.key_id IN (1,2...) )                 
 WHEN MATCHED THEN UPDATE SET t1.key_id = CASE WHEN t1.key_id = t2.key_id THEN
                                                    t1.key_id + 100
                                               ELSE
                                                    t1.id
                                                END 

Demo

  • UPDATE.. SET... FROM.. syntax is not supported within Oracle DB unlike to some other well-known DBM Systems
  • The former Join syntax containing comma-seperated tables shouldn't be used rather the SQL-92 syntax with explicit JOIN keywords should be preferred as being easier to use whenever a Join statement is needed

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