ORA-01427:单行子查询在Update语句中返回多个行

时间:2018-08-24 08:27:48

标签: sql oracle for-loop update-statement

ORA-01427:单行子查询在更新语句中返回多个行

嗨。对于以下查询,发生ORA-01427错误。

我正在尝试从country_population获取生日并将其设置为city_population中的fave_date。不需要其他更简单的方法来执行此操作,我只需要一些有关如何消除错误并使查询工作的建议。 谢谢:)

    DECLARE
            CURSOR custCur IS
                     SELECT name, age, weight, height, birthday FROM country_population;
            CNTR number(9) := 0;
    BEGIN
            FOR curRec IN custCur LOOP

                    UPDATE city_population srvagr
                    SET     srvagr.date1 = SYSDATE,
                            srvagr.fave_date =
                                            (select curRec.birthday from country_population curRec
                                            where srvagr.name=curRec.name
                                            and srvagr.age=curRec.age
                                            and srvagr.weight=curRec.weight
                                            and srvagr.height=curRec.height),
                            srvagr.date2 = SYSDATE,
                            srvagr.date3 = SYSDATE,
                            srvagr.status = 'visitor',
                            srvagr.note = 'Noted'
                    WHERE
                            srvagr.name = curRec.name
                            and srvagr.age = curRec.age
                            and srvagr.weight = curRec.weight
                            and srvagr.height = curRec.height
                            and srvagr.status != 'visitor'
                            and srvagr.fave_date is null;

                    CNTR := CNTR + 1;
                    if CNTR = 1000
                            then
                                    COMMIT;
                                    CNTR := 0;
                    end if;

            END LOOP;

            COMMIT;

1 个答案:

答案 0 :(得分:3)

查询

(select curRec.birthday from country_population curRec
                      where srvagr.name=curRec.name
                      and srvagr.age=curRec.age
                      and srvagr.weight=curRec.weight
                      and srvagr.height=curRec.height) 

返回不止一行,因此您不能使用均等的..

在这种情况下,您可以在条件仅获取行结果的地方添加更多选择

或者,如果没有一个结果,只能使用聚合函数来减少结果,例如:min()或max()

(select min(curRec.birthday)  from country_population curRec
                      where srvagr.name=curRec.name
                      and srvagr.age=curRec.age
                      and srvagr.weight=curRec.weight
                      and srvagr.height=curRec.height
                      ) 

或对行结果使用限制

(select min(curRec.birthday)  from country_population curRec
                      where srvagr.name=curRec.name
                      and srvagr.age=curRec.age
                      and srvagr.weight=curRec.weight
                      and srvagr.height=curRec.height
                      and rownum = 1)