我有一张名为养恤金的表格,有以下数据
PERSNO MMYY AMT STNO
C01234 0120 1000 null
C01234 0220 1100 null
C01234 0320 1050 null
C02563 0120 1000 null
C02563 0220 950 null
C02563 0320 1200 null我有另一个表雇员,有以下数据
PERSNO STNO
C01234 1521
C02563 2365
C01891 2593当养老金表的PERSNO字段与员工表的字段匹配时,我需要用EMPLOYEE表的STNO字段的值更新养老金表的STNO字段。
请有人建议我使用SQL查询在Oracle中执行此操作。
发布于 2021-01-22 10:24:59
一个不错的MERGE选项:
merge into pension p
using employee e
on (p.persno = e.persno)
when matched then
update set p.stno = e.stno;使用您发布的示例数据(稍微修改一下;不想输入那么多):
SQL> select * From pension;
PERSNO STNO AMT
------ ---------- ----------
c01234 1
c01234 3
c01234 5
c02563 2
c02563 9
c02563 2
6 rows selected.
SQL> select * From employee;
PERSNO STNO
------ ----------
c01234 1521
c02563 2365
c01891 2593
SQL> merge into pension p
2 using employee e
3 on (p.persno = e.persno)
4 when matched then
5 update set p.stno = e.stno;
6 rows merged.
SQL> select * from pension;
PERSNO STNO AMT
------ ---------- ----------
c01234 1521 1
c01234 1521 3
c01234 1521 5
c02563 2365 2
c02563 2365 9
c02563 2365 2
6 rows selected.
SQL>但是,如果在PERSNO表中有一个重复的EMPLOYEE:
SQL> select * from employee order by persno;
PERSNO STNO
------ ----------
c01234 1521 --> two rows for
c01234 9999 --> c01234
c01891 2593
c02563 2365查询不再工作,因为它无法决定使用这两行中的哪一行。你知道吗?如果是的话,告诉我们。或者,如果不允许复制,那么摆脱它们,merge将再次工作。
SQL> merge into pension p
2 using employee e
3 on (p.persno = e.persno)
4 when matched then
5 update set p.stno = e.stno;
merge into pension p
*
ERROR at line 1:
ORA-30926: unable to get a stable set of rows in the source tables
SQL>如果您决定选择例如MIN(EMPLOYEE.STNO)值,则将查询重写为
SQL> merge into pension p
2 using (select e.persno, min(e.stno) stno
3 from employee e
4 group by e.persno
5 ) x
6 on (p.persno = x.persno)
7 when matched then
8 update set p.stno = x.stno;
6 rows merged.
SQL>它会再起作用的。
https://stackoverflow.com/questions/65843343
复制相似问题