5

I'm trying to create a simple stored procedure that stores queried result into one string.

v_string1 varchar2(100);

Select column1
From dual;

Will return

column 1
--------
aaaa
bbbb
cccc

I want to store "aaaa, bbbb, cccc' into v_string1. And all I can think of is a Cursor... Is there a better way to handle this?

sayhaha
  • 769
  • 3
  • 12
  • 25
  • possible duplicate of [alternative to listagg in Oracle?](http://stackoverflow.com/questions/9412512/alternative-to-listagg-in-oracle) – DCookie Jun 08 '12 at 19:04

2 Answers2

21

Using SQL Fiddle:

select LISTAGG(name, ',') WITHIN GROUP (ORDER BY 1) AS names
from temp_table
Kyra
  • 5,129
  • 5
  • 35
  • 55
1

Another option using pure SQL that will work before Oracle 11G, although is still limited to 4000 characters for the string.

Select ltrim(max(names), ', ') as names
From (
  Select sys_connect_by_path(name, ' ,') as names
  From (
    Select name, row_number() over (order by name) as rown
    From temp_table
  )
  Start with rown = 1
  Connect by rown = prior rown + 1
)
Mike Meyers
  • 2,885
  • 1
  • 20
  • 26