基于rownum的Oracle更新

时间:2017-04-14 18:02:59

标签: sql oracle

我需要编写oracle sql,使用rownum从不相关的表中更新值。

我无法让它发挥作用:

ip_details* ips_details=0;
int ips_details_len;
get_ip_details(&ips_details, &ips_details_len);
for(int i=0; i < ips_details_len; i++){
    cout << string(ips_details[i].name) << "-"<< 
    string(ips_details[i].ip_address) << "-"  << 
    string(ips_details[i].mac_address) << "-" << 
    ips_details[i].Flags << endl;

}

感谢。

只需要将列ID中的值插入另一个表即可。没有列可以用于连接但是rownum。 这有可能吗?

1 个答案:

答案 0 :(得分:1)

使用MERGE语句而不是UPDATE 请在下面找到一个简单的例子。

首先测试数据(id中的table_2列为空):

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 

这是MERGE命令,复印机id根据它们的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;

合并后的结果是:

SELECT * FROM table_2;
        ID NAME
---------- ----
         1 A   
         2 B   
         3 C   
         4 D   
         5 E