如何从批量收集中检索多个列的数据

时间:2016-01-24 18:13:21

标签: plsql

DECLARE
   TYPE two_cols IS RECORD
   (
      family_id   family_members.family_id %TYPE,
      city     family_members.city%TYPE
   );

   TYPE family_members_t IS TABLE OF two_cols;

   l_family_members   family_members_t;
BEGIN
   SELECT family_id,city 
   BULK COLLECT INTO l_family_members
   FROM (SELECT x.family_id, x.City, x.Member_count,row_number() 
         OVER (PARTITION BY x.family_id ORDER BY x.Member_count DESC) rn
         FROM (SELECT family_id, City, COUNT(*) Member_count
               FROM FAMILY_MEMBERS
               GROUP BY family_id, City) x) y
   WHERE y.rn = 1;

   for rec in 1..l_family_members.count 
   loop
       dbms_output.put_line('majority mem of family id' 
           || l_family_members.family_id(rec)
           || 'stay in '||l_family_members.city(rec));
   end loop;
END;

错误:

  

ORA-06550:第23行,第69栏:PLS-00302:组件'FAMILY_ID'必须   声明为ORA-06550:第23行,第1列:PL / SQL:语句被忽略   06550. 00000 - “行%s,列%s:\ n%s”   *原因:通常是PL / SQL编译错误。   *操作:

我对输出行很困惑..我没有得到如何从批量收集中检索数据,因为它有两列...如何区分它们并检索它们?

1 个答案:

答案 0 :(得分:-1)

你试图在1条记录中选择2列不起作用。 根据您的数据库版本,您可以选择然后将批量收集到表中的记录,如下所示

DECLARE
   TYPE two_cols IS RECORD
   (
      family_id   family_members.family_id %TYPE,
      city     family_members.city%TYPE
   );

   TYPE family_members_t IS TABLE OF two_cols;

   l_family_members   family_members_t;
BEGIN
   SELECT two_cols(family_id,city )
   BULK COLLECT INTO l_family_members
   FROM (SELECT x.family_id, x.City, x.Member_count,row_number() 
         OVER (PARTITION BY x.family_id ORDER BY x.Member_count DESC) rn
         FROM (SELECT family_id, City, COUNT(*) Member_count
               FROM FAMILY_MEMBERS
               GROUP BY family_id, City) x) y
   WHERE y.rn = 1;

   for rec in 1..l_family_members.count 
   loop
       dbms_output.put_line('majority mem of family id' 
           || l_family_members(rec).family_id
           || 'stay in '||l_family_members(rec).city);
   end loop;
END;

注意:我还修改了输出循环中的引用,将(rec)放在表之后和列之前