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?

1

2 Answers 2

22

Using SQL Fiddle:

select LISTAGG(name, ',') WITHIN GROUP (ORDER BY 1) AS names
from temp_table
Sign up to request clarification or add additional context in comments.

2 Comments

Coolio...I've never seen that function before +1!
Thanks. I hadn't either until I googled it. Glad it helped and it caused me to learn something new too :D
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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.