如果用SQL,需要写自定义聚集函数,例如:<br><br>Oracle的定制功能十分强大。前几天在碰到一个问题的时候,查询文档发现,oracle不但允许用户定制自己的函数,还可以定制自己的聚集函数和分析函数。<br><br>下面是我使用自定义聚集函数建立一个字符串“sum”的小例子。<br><br>SQL> CREATE OR REPLACE TYPE T_LINK AS OBJECT ( <br> 2 STR VARCHAR2(30000), <br> 3 STATIC FUNCTION ODCIAGGREGATEINITIALIZE(SCTX IN OUT T_LINK) RETURN NUMBER, <br> 4 MEMBER FUNCTION ODCIAGGREGATEITERATE(SELF IN OUT T_LINK, VALUE IN VARCHAR2) RETURN NUMBER, <br> 5 MEMBER FUNCTION ODCIAGGREGATETERMINATE(SELF IN T_LINK, RETURNVALUE OUT VARCHAR2, FLAGS IN NUMBE<br>R) RETURN NUMBER, <br> 6 MEMBER FUNCTION ODCIAGGREGATEMERGE(SELF IN OUT T_LINK, CTX2 IN T_LINK) RETURN NUMBER <br> 7  
<br> 8 / <br><br><br>类型已创建。<br><br><br>SQL> CREATE OR REPLACE TYPE BODY T_LINK IS <br> 2 STATIC FUNCTION ODCIAGGREGATEINITIALIZE(SCTX IN OUT T_LINK) RETURN NUMBER IS <br> 3 BEGIN <br> 4 SCTX := T_LINK(NULL); <br> 5 RETURN ODCICONST.SUCCESS; <br> 6 END; <br> 7 <br> 8 MEMBER FUNCTION ODCIAGGREGATEITERATE(SELF IN OUT T_LINK, VALUE IN VARCHAR2) RETURN NUMBER IS <br> 9 BEGIN <br> 10 SELF.STR := SELF.STR || VALUE; <br> 11 RETURN ODCICONST.SUCCESS; <br> 12 END; <br> 13 <br> 14 MEMBER FUNCTION ODCIAGGREGATETERMINATE(SELF IN T_LINK, RETURNVALUE OUT VARCHAR2, FLAGS IN NUMBE<br>R) RETURN NUMBER IS <br> 15 BEGIN <br> 16 RETURNVALUE := SELF.STR; <br> 17 RETURN ODCICONST.SUCCESS;<br> 18 END; <br> 19 <br> 20 MEMBER FUNCTION ODCIAGGREGATEMERGE(SELF IN OUT T_LINK, CTX2 IN T_LINK) RETURN NUMBER IS <br> 21 BEGIN <br> 22 NULL; <br> 23 RETURN ODCICONST.SUCCESS; <br> 24 END; <br> 25 END; <br> 26 / <br><br><br>类型主体已创建。<br><br><br>SQL> CREATE OR REPLACE FUNCTION F_LINK(P_STR VARCHAR2) RETURN VARCHAR2 <br> 2 AGGREGATE USING T_LINK; <br> 3 /<br><br><br>函数已创建。<br><br><br>SQL> CREATE TABLE TEST (ID NUMBER, NAME VARCHAR2(20));<br><br><br>表已创建。<br><br><br>SQL> INSERT INTO TEST VALUES (1, 'AAA');<br><br><br>已创建 1 行。<br><br><br>SQL> INSERT INTO TEST VALUES (2, 'BBB');<br><br><br>已创建 1 行。<br><br><br>SQL> INSERT INTO TEST VALUES (1, 'ABC');<br><br><br>已创建 1 行。<br><br><br>SQL> INSERT INTO TEST VALUES (3, 'CCC');<br><br><br>已创建 1 行。<br><br><br>SQL> INSERT INTO TEST VALUES (2, 'DDD');<br><br><br>已创建 1 行。<br><br><br>SQL> COMMIT;<br><br><br>提交完成。<br><br><br>SQL> COL NAME FORMAT A60<br><br><br>SQL> SELECT ID, F_LINK(NAME) NAME FROM TEST GROUP BY ID;<br><br><br> ID NAME<br>---------- ------------------------------------------------------<br> 1 AAAABC<br> 2 BBBDDD<br> 3 CCC