How can I return a CSV string from PL/SQL table type in Oracle

雨燕双飞 提交于 2020-01-05 10:39:32

问题


I have defined a table type PL/SQL variable and added some data there.

create or replace type varTableType as table of varchar2(32767);
my_table varTableType := varTableType()
...
my_table := some_function();

Now I have this my_table table type variable with several thousands of records. I have to select only those records ending with specific character, say 'a' and get results in a comma separated string. I think that COLLECT function could do this, but I do not understand exactly how. I am using Oracle 10g.


回答1:


Without getting into the question- why are you using a table type and not a table (or temporary table), you can do it like this:

declare
  my_table varTableType;
  i varchar2(32767);
begin
  my_table := new
              varTableType('bbbb', 'ccca', 'ddda', 'eee', 'fffa', 'gggg');

  select trim(xmlagg(xmlelement(e, column_value || ','))
              .extract('//text()'))
    into i
    from table(my_table)
   where column_value like '%a';

  dbms_output.put_line(i);

end;

There are more ways to concat rows- WM_CONCAT (if enabled) or LISTAGG (since 11g R2) but the basic idea of

select column_value 
from table(my_table) 
where column_value like '%a';

stays


There is another way without sql:

declare
  my_table varTableType;
  i varchar2(32767);
begin
  my_table := new
              varTableType('bbbb', 'ccca', 'ddda', 'eee', 'fffa', 'gggg');

  FOR j IN my_table.first .. my_table.last LOOP

     IF my_table(j) like '%a' THEN
        i := i || my_table(j);
     END IF;

  END LOOP;

  dbms_output.put_line(i);

end;



回答2:


See this blog post by Tim Hall for a number of ways to do this, depending on Oracle version.



来源:https://stackoverflow.com/questions/10997854/how-can-i-return-a-csv-string-from-pl-sql-table-type-in-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!