Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

oracle pl/sql results into one string

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?

like image 984
sayhaha Avatar asked Jun 08 '12 18:06

sayhaha


People also ask

How do you concatenate in PL SQL?

The CONCAT function allows you to concatenate two strings together. To CONCAT more than two values, we can nest multiple CONCAT function calls. Parameters Used: string1: It is used to specify the first string to concatenate.

How do I print a string in PL SQL?

How do I print a string in PL SQL? v_length Loop v_out := substr(IN_string,i,1) ; DBMS_OUTPUT. PUT_LINE(v_out); End loop; DBMS_OUTPUT. PUT_LINE('Text printed: ' || IN_string); End; — Procedure created.

Which function is used to combine the string in Oracle?

There are two ways to concatenate Strings in Oracle SQL . Either using CONCAT function or || operator. SELECT CONCAT( string1, string2 ) FROM dual; Since CONCAT function will only allow you to concatenate two values together.


2 Answers

Using SQL Fiddle:

select LISTAGG(name, ',') WITHIN GROUP (ORDER BY 1) AS names
from temp_table
like image 102
Kyra Avatar answered Oct 14 '22 23:10

Kyra


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
)
like image 25
Mike Meyers Avatar answered Oct 15 '22 00:10

Mike Meyers