简体   繁体   中英

How to fix Ora-01427 single-row subquery returns more than one row in Update statement?

Here is my query:

UPDATE CIELA_STATUS 
SET CIELA_STATUS.OSIGURENI = (
  SELECT STG5.OSIGURENI
  FROM CIELA_STATUS_STG5 STG5
  WHERE CIELA_STATUS.UIC = STG5.UIC)
WHERE EXISTS (
  SELECT STG5.OSIGURENI
  FROM CIELA_STATUS_STG5 STG5
  WHERE CIELA_STATUS.UIC = STG5.UIC
  AND nvL(CIELA_STATUS.OSIGURENI, 9999) <> STG5.OSIGURENI)

As the error says the subquery used to set the updated column produced more than one row.

The most probably explanation is that the UIC column is not a primary/unique key in the table CIELA_STATUS_STG5

Quick check

select UIC, count(*)
from CIELA_STATUS_STG5
group by UIC
having count(*) > 1

You'll see the duplicated keys and you must decide how to recover. Eg delete duplicates, or use only MAX value in the update or use the newes/oldest rows etc.

Note - to more focused selection of the duplicates, as you do not use the whole table CIELA_STATUS_STG5 in the update use this query, which makes the same restriction as used in the update:

SELECT 
  STG5.UIC, count(*) cnt
FROM CIELA_STATUS_STG5 STG5
WHERE  STG5.UIC IN (
SELECT  CIELA_STATUS.UIC
FROM CIELA_STATUS 
WHERE EXISTS
      (SELECT STG5.OSIGURENI
                         FROM CIELA_STATUS_STG5 STG5
                         WHERE  CIELA_STATUS.UIC = STG5.UIC
                         AND nvL(CIELA_STATUS.OSIGURENI,9999) <> STG5.OSIGURENI)
)
GROUP BY STG5.UIC
HAVING count(*) > 1;

The problem is this part of your query:

SELECT STG5.OSIGURENI
FROM CIELA_STATUS_STG5 STG5
WHERE CIELA_STATUS.UIC = STG5.UIC

Is returning multiple rows. You need a way to pick exactly one row from the many for the insert.

If it gives an acceptable result, the easiest way is to use MIN() or MAX() :

SELECT MAX(STG5.OSIGURENI)
FROM CIELA_STATUS_STG5 STG5
WHERE CIELA_STATUS.UIC = STG5.UIC

So your whole query would then be:

UPDATE CIELA_STATUS 
SET CIELA_STATUS.OSIGURENI = (
  SELECT MAX(STG5.OSIGURENI)
  FROM CIELA_STATUS_STG5 STG5
  WHERE CIELA_STATUS.UIC = STG5.UIC)
WHERE EXISTS (
  SELECT STG5.OSIGURENI
  FROM CIELA_STATUS_STG5 STG5
  WHERE CIELA_STATUS.UIC = STG5.UIC
  AND nvL(CIELA_STATUS.OSIGURENI, 9999) <> STG5.OSIGURENI)

If MAX() doesn't give the proper result, you'll have to engineer a query that selects the appropriate row from the many that match.

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