问题
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