繁体   English   中英

pl sql用同一表中的值更新行

[英]pl sql update rows with value from the same table

在座席表中,我的字段bossId是其他座席的ID,因此我为座席表中的所有其他字段生成了数据,现在我需要为所有行设置bossId。

因此,每一行都需要从同一张表中为其bossId字段选择agentId。 可能有一些特工同一个老板,但特工不能是他自己的老板。

这是我的桌子

+---------+------+--------+
| agentId | name | bossId |
+---------+------+--------+
|     123 | aaa  |        |
|     124 | bbb  |        |
|     125 | ccc  |        |
|     126 | ddd  |        |
+---------+------+--------+

想要的转售:

+---------+------+--------+
| agentId | name | bossId |
+---------+------+--------+
|     123 | aaa  |    124 |
|     124 | bbb  |    123 |
|     125 | ccc  |    126 |
|     126 | ddd  |    123 |
+---------+------+--------+

所以空列bossId需要用同一表的AgentId填充如何在pl sql中做到这一点?

更新:尝试使用此代码似乎没问题,但出现错误

begin
  for i in 1..17 loop
    update policeman p
    set bossid = (select p2.officerid
                 from policeman p2
                 order by dbms_random.value
                 where rownum = 1)
                 where rownum =i;
    end loop;
    end ;

错误:

ORA-06550: line 6, column 18:
PL/SQL: ORA-00907: missing right parenthesis
ORA-06550: line 3, column 5:
PL/SQL: SQL Statement ignored

这是您想要的吗?

update t
    set bossid = (select max(bossid) keep (dense_rank first order by dbms_random.random)
                  from t
                 );

注意:如果您的数据不小,这可能不是很有效。

只要agentid是唯一的,这应该可以工作。

update t tgt set bossid = (select max(agentid) from t src where tgt.agentid<>src.agentid);

暂无
暂无

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

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