I need to write oracle sql to update column with value from unrelated table using rownum.
I cannot get it work:
UPDATE table_1 A
SET A.id = (SELECT B.id FROM table_2 B
WHERE A.rownum = B.rownum)
Thanks.
Just need to insert value from column ID to another table. There is no columns which are I can use for join but rownum. Is this is possible?
Use MERGE statement instead of UPDATE.
Please find a simple example below.
Test data first ( id
column in table_2
is null):
create table table_2 as
SELECT LEVEL as id, chr(64+level) as name
from dual connect by level <= 5;
create table table_1 as select * from table_2;
update table_2 set id = null;
commit;
SELECT * FROM table_1;
ID NAME
---------- ----
1 A
2 B
3 C
4 D
5 E
SELECT * FROM table_2;
ID NAME
---------- ----
A
B
C
D
E
This is MERGE command that copier id
values from one table to second one basing on their rownumns:
MERGE INTO table_2 t2
USING (
SELECT *
FROM (
select t.*, rownum as rn
from table_1 t
) t1
JOIN (
select rownum as rn, rowid as rid
from table_2 t
) t2
ON t1.rn = t2.rn
) d
ON ( t2.rowid = d.rid )
WHEN MATCHED THEN UPDATE SET t2.id = d.id;
And a result after merge is:
SELECT * FROM table_2;
ID NAME
---------- ----
1 A
2 B
3 C
4 D
5 E
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.