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

时间:2019-03-19 12:52:25

标签: sql oracle plsql

在座席表中,我有一个字段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

2 个答案:

答案 0 :(得分:1)

这是您想要的吗?

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

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

答案 1 :(得分:0)

如果agentid是唯一的,这应该可以工作。

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

相关问题