返回超过请求的行

时间:2016-05-07 04:48:35

标签: sql oracle

我有这个PL / SQL函数:

Create Or Replace Function mostMealOrders
Return varchar
Is

name_phone varchar(200) := ' ';

Cursor c1 Is
        Select acctid  
        From MealOrder Natural Join Customer
        Group By acctid
        Having Count(*) >= All (Select Count(*)
                                From MealOrder
                                Group By acctid);

Begin
        For acctNum in c1
        Loop
                Select (name || ' ' || phone || ', ')
                Into name_phone
                From Customer
                Where acctid = acctNum.acctid;
        End Loop
        Return name_phone;
End;
/
Show Errors;

当我运行上面的代码时,我收到此错误:

exact fetch returns more than requested number of rows

子查询尝试查找来自acctId的订单数量最多的OrderTable

子查询返回多个acctid,因此我相信这就是我收到错误的原因。有没有人知道如何获取子查询返回的所有acctid's的名称和电话,正如我在外部查询中尝试的那样?

1 个答案:

答案 0 :(得分:2)

您可以使用光标,如下所示:

FOR rec in (
    Select (name || ' ' || phone || ',') AS name_phone
    From Customer
    Where acctid in (Select acctid    
                     From OrderTable Natural Join Customer
                     Group By acctid
                     Having Count(*) >= All (
                                Select Count(*)
                                From OrderTable
                                Group By acctid))
) LOOP
     -- do something with rec.name_phone
     dbms_output.put_line(rec.name_phone);
END LOOP;

但是,如果您要查找将所有检索到的字符串连接到一个长字符串的循环,请使用LISTAGG函数:

Select LISTAGG (name || ' ' || phone, ',') 
       WITHIN GROUP (ORDER BY name, phone)
Into name_phone
From Customer
Where acctid in (Select acctid    
                 From OrderTable Natural Join Customer
                 Group By acctid
                 Having Count(*) >= All (
                            Select Count(*)
                            From OrderTable
                            Group By acctid))