avr
02
2009
0

MySQL group_contat in ORACLE

Here is a way to add the group_concat function to ORACLE. After that you’ll be able to do just like in MySQL.

first you’ll need to create a new object type:


create or replace TYPE t_string_agg AS OBJECT
(
g_string VARCHAR2(32767),

STATIC FUNCTION ODCIAggregateInitialize(sctx IN OUT t_string_agg)
RETURN NUMBER,

MEMBER FUNCTION ODCIAggregateIterate(self IN OUT t_string_agg,
value IN VARCHAR2 )
RETURN NUMBER,

MEMBER FUNCTION ODCIAggregateTerminate(self IN t_string_agg,
returnValue OUT VARCHAR2,
flags IN NUMBER)
RETURN NUMBER,

MEMBER FUNCTION ODCIAggregateMerge(self IN OUT t_string_agg,
ctx2 IN t_string_agg)
RETURN NUMBER
);

then create a function using the newly created type :


create or replace FUNCTION tring_concat (p_input VARCHAR2)
RETURN VARCHAR2
PARALLEL_ENABLE AGGREGATE USING t_string_agg;

now try it with SCOTT’s schema


COLUMN employees FORMAT A50

SELECT deptno, group_concat(ename) AS employees
FROM emp
GROUP BY deptno;

DEPTNO EMPLOYEES
---------- --------------------------------------------------
10 CLARK,KING,MILLER
20 SMITH,FORD,ADAMS,SCOTT,JONES
30 ALLEN,BLAKE,MARTIN,TURNER,JAMES,WARD

3 rows selected.

that could be quite useful to add this function to the SYS schema and then create a public synonym. this way the function will be available to any user of the database.

Written by admin in: oracle | Mots-clefs :, , ,