why would you want to write plsql code - just use sql.
You can either
a) search this site for stragg and once installed:
ops$tkyte%ORA11GR2> l
1* select deptno, stragg(ename) enames from scott.emp group by deptno
ops$tkyte%ORA11GR2> /
DEPTNO ENAMES
---------- ----------------------------------------
10 CLARK,MILLER,KING
20 SMITH,FORD,ADAMS,SCOTT,JONES
30 ALLEN,JAMES,TURNER,BLAKE,MARTIN,WARD
that works in 9i and above.
b) in 10g and above, you could
ops$tkyte%ORA11GR2> select deptno,
2 max(sys_connect_by_path(ename,',')) enames
3 from (
4 select deptno, ename, row_number() over (partition by deptno order by ename) rn
5 from scott.emp
6 )
7 start with rn = 1
8 connect by prior deptno = deptno and prior rn+1 = rn
9 group by deptno
10 /
DEPTNO ENAMES
---------- ----------------------------------------
30 ,ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD
20 ,ADAMS,FORD,JONES,SCOTT,SMITH
10 ,CLARK,KING,MILLER
c) or in 11g and above you would simply:
ops$tkyte%ORA11GR2> select deptno,
2 listagg( ename, ',' ) within group (order by ename) enames
3 from scott.emp
4 group by deptno
5 /
DEPTNO ENAMES
---------- ----------------------------------------
10 CLARK,KING,MILLER
20 ADAMS,FORD,JONES,SCOTT,SMITH
30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD