Oracle Function: Replicate wm_concat

前提是你 提交于 2019-12-05 11:57:19

Do you get an error message when you use wm_concat? Unlike functions like to_char, it is owned by wmsys and you might need to use wmsys.wm_concat to use it. (unless you create the necessary synonyms of course).

Now for the actual question,

This technique is called string aggregation.

You could find a lot of other alternatives here.

http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php For other methods, Search for "stragg" on http://asktom.oracle.com Another useful link : http://www.orafaq.com/node/2290

This is probably the most used one. A lot of teams write their own custom functions which more or less do the same.

CREATE OR REPLACE FUNCTION get_employees (p_deptno  in  emp.deptno%TYPE)
  RETURN VARCHAR2
IS
  l_text  VARCHAR2(32767) := NULL;
BEGIN
  FOR cur_rec IN (SELECT ename FROM emp WHERE deptno = p_deptno) LOOP
    l_text := l_text || ',' || cur_rec.ename;
  END LOOP;
  RETURN LTRIM(l_text, ',');
END;
/
SHOW ERRORS

while this solution works for varchar2 and number, the best generic solution can be built using Oracle ODCIAggregate interface.

http://download-west.oracle.com/docs/cd/B14117_01/appdev.101/b10800/dciaggfns.htm#sthref462

Implementation for the same is at the first link above at www.oracle-base.com

I've solved this using a technique similar to the last one in the oracle-base article: define a custom TABLE type and write a function to aggregate a value of that type into a string. I called my function joinstr and then you can call it as follows:

SELECT joinstr(CAST(MULTISET(SELECT column1 FROM table1) AS my_string_table_type), ',') 
FROM DUAL

Note: I was on 9i until recently and haven't looked into COLLECT yet.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!