简体   繁体   中英

Oracle sql update with table join giving error

I am running the following Oracle update statement and getting error:

ORA-01427: single-row subquery returns more than one row

UPDATE Maximo.laborcraftrate lcr
SET lcr.controlaccount = (SELECT c.mxrcontrolaccount
                     FROM maximo.contract c
                     WHERE lcr.contractnum = c.CONTRACTNUM)
WHERE EXISTS (SELECT controlaccount
              FROM maximo.contract c
              WHERE lcr.contractnum = c.contractnum);   

Does anyone know how to limit the subquery?

EDIT:

Here is a select statement showing the join between the tables. What I am trying to do is update the a.controlaccount with b.controlaccount under these conditions:

CRAFT   CONTRACTNUM CONTROLACCOUNT  MXRCONTROLACCOUNT
TR-CHNDI    TR-GENERAL      01-3010-72515
TR-CHNDP             TR-GENERAL     01-3010-72515
TR-CHNDI             TR-GENERAL     01-3010-72515
TR-CHNDI             TR-GENERAL     01-3010-72515
TR-CHNDP             TR-GENERAL     01-3010-72515
TR-FENI          TR-GENERAL     01-3010-72515
select a.craft,a.contractnum,a.controlaccount,b.mxrcontrolaccount
from maximo.laborcraftrate a
left join maximo.contract b on a.contractnum = b.contractnum
where a.contractnum is not null

What don't you understand about the error? The subquery is returning more than one row.

One simple solution is to just add and rownum = 1 :

UPDATE Maximo.laborcraftrate lcr
    SET lcr.controlaccount = (SELECT c.mxrcontrolaccount
                              FROM maximo.contract c
                              WHERE lcr.contractnum = c.CONTRACTNUM AND rownum = 1
                             )
    WHERE EXISTS (SELECT controlaccount
                  FROM maximo.contract c
                  WHERE lcr.contractnum = c.contractnum);  

Or to use an aggregation function. Both of these guarantee at most one row. However, this problem is not necessarily amenable to simple fixes. Often there is a logical issue.

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.

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