1.sql提供以下两种查询方式
来拼接同一个字段多个记录结果
1.replace+wm_concat 2.listagg within group
两种方式可实现一样的效果。
快速脚本:替换 表名 与 字段名 执行即可验证。
select ( -- 1.replace+wm_concat select replace(wm_concat(a.name),',','|') from teacher_leader a ) res1, -- 2.listagg within group ( select listagg(a.name,'|') within group (order by a.name) from teacher_leader a ) res2 from dual;
实测:
2.如果报错
ora-00904: “wm_concat”: 标识符无效
可进行如下处理解决,定义type部分参考
注意: 如果你没有system用户,可能是一个用户拥有多个角色,那么上面的参考博客对你不适用。
可用下面的方案:
2.1作为sysdba角色登录
2.2 给普通用户授权
grant create type to shop; grant create procedure to shop;
登录shop(以普通用户normal的身份登录)
2.3 创建type并创建函数【wm_concat】
--在shop用户作为normal角色会话下创建可用的wm_concat函数,直接执行以下语句 --定义类型 create or replace type wm_concat_impl as object ( curr_str varchar2(32767), static function odciaggregateinitialize(sctx in out wm_concat_impl) return number, member function odciaggregateiterate(self in out wm_concat_impl, p1 in varchar2) return number, member function odciaggregateterminate(self in wm_concat_impl, returnvalue out varchar2, flags in number) return number, member function odciaggregatemerge(self in out wm_concat_impl, sctx2 in wm_concat_impl) return number ); / --定义类型body: create or replace type body wm_concat_impl is static function odciaggregateinitialize(sctx in out wm_concat_impl) return number is begin sctx := wm_concat_impl(null) ; return odciconst.success; end; member function odciaggregateiterate(self in out wm_concat_impl, p1 in varchar2) return number is begin if(curr_str is not null) then curr_str := curr_str || ',' || p1; else curr_str := p1; end if; return odciconst.success; end; member function odciaggregateterminate(self in wm_concat_impl, returnvalue out varchar2, flags in number) return number is begin returnvalue := curr_str ; return odciconst.success; end; member function odciaggregatemerge(self in out wm_concat_impl, sctx2 in wm_concat_impl) return number is begin if(sctx2.curr_str is not null) then self.curr_str := self.curr_str || ',' || sctx2.curr_str ; end if; return odciconst.success; end; end; / --自定义行变列函数: create or replace function wm_concat(p1 varchar2) return varchar2 aggregate using wm_concat_impl ; /
2.4 最后一步,创建同义词及授权
--创建完成,给其创建同义词及授权,以供其他用户能正常使用。 create public synonym wm_concat_impl for shop.wm_concat_impl / create public synonym wm_concat for shop.wm_concat / grant execute on wm_concat_impl to public / grant execute on wm_concat to public /
验证
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论