自定义聚合函数

在项目开发过程中遇到将多条记录合并为一条记录的需求,这时原来的聚合函数己经不能满足我们的要求,于是在网上找到了一个聚合函数的实例供大家使用及更改更好的函数。下面创建应用的表结构并构建相应的数据。

create table jl_test
(
name varchar2(200),
id number(2),
depno number(2)
);
insert into jl_test values ('admin',1,2);
insert into jl_test values ('root',1,2);
commit;
select strcat(name),id,depno from jl_test group by id,depno;
-- 1 admin,root 1 2

1.创建类型定义

create or replace type strcat_type as object
      (
        currentstr varchar2(4000),
        currentseprator varchar2(8),
        static function ODCIAggregateInitialize(sctx IN OUT strcat_type) return number,
        member function ODCIAggregateIterate(self IN OUT strcat_type,value IN VARCHAR2) return number,
        member function ODCIAggregateTerminate(self IN strcat_type,returnValue OUT VARCHAR2, flags IN number) return number,
        member function ODCIAggregateMerge(self IN OUT strcat_type,ctx2 IN strcat_type) return number
      );

2.创建类型体及类体函数

create or replace type body strcat_type is
      static function ODCIAggregateInitialize(sctx IN OUT strcat_type) return number is
      begin
        sctx := strcat_type('',',');
        return ODCIConst.Success;
      end;
      member function ODCIAggregateIterate(self IN OUT strcat_type, value IN VARCHAR2) return number is
      begin
        if self.currentstr is null then
           self.currentstr := value;
        else
          self.currentstr := self.currentstr ||currentseprator || value;
        end if;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateTerminate(self IN strcat_type, returnValue OUT VARCHAR2, flags IN number) return number is
      begin
        returnValue := self.currentstr;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateMerge(self IN OUT strcat_type, ctx2 IN strcat_type) return number is
      begin
        if ctx2.currentstr is null then
          self.currentstr := self.currentstr;
        elsif self.currentstr is null then
          self.currentstr := ctx2.currentstr;
        else
          self.currentstr := self.currentstr || currentseprator || ctx2.currentstr;
        end if;
        return ODCIConst.Success;
      end;
      end;

3.创建实例函数

CREATE OR REPLACE FUNCTION strcat (input VARCHAR2) RETURN VARCHAR2 PARALLEL_ENABLE AGGREGATE USING strcat_type;

 

以上内容均为网上一些人己经写好的,我只是拿过来应用而己,哈哈

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值