oracle 自定义函数创建

create or replace function GetWtlxname(guidname in varchar2)
--定义参数
return  varchar2 as
pwtlxname varchar2(2000);

begin
--将行转换成列
select wm_concat(wtlxname) wtlxname
into  pwtlxname
 from (
select guid,incident,wtlx,case wtlx when '1' then '审批时间过长' when '2' then '供应商接收时间过长' when '3' then '发货时间过长' when '4' then '收货时间过长'
 when '5' then '超时评价' when '6' then '服务问题' when '7' then '质量问题' when '8' then '送货速度问题' when '10' then  '物流时间过长' else '其它' end wtlxname
 from (
      select guid,incident,
       --regexp_substr(str,reg,起始位置 第几次)
       regexp_substr(wtlx, '[^,]+', 1, level) wtlx
      from sgs_zhgl_ddscyybzpt
      connect by level <= regexp_count(wtlx, ',') + 1
      --regexp_count(teachers, ',') 统计字符串中,的数量
      and guid = prior guid
      --你能理解CONNECT BY吧?它相当于是一个递归的自连接,不断地把每层的连接结果叠加到结果集中。两层之间的连接条件和递归出口写在CONNECT BY中。在这里我们的数据并无父子关系,只是要让同一行数据重复出现,因此我们的连接的条件只用到了表的主键id=PRIOR id, 此外再用LEVEL控制层数作为递归出口。但ORACLE有个检查,如果你有前后连接条件(id=PRIOR id),但是同一行数据再次出现,它就会报一个错:
      --ERROR:
      --ORA-01436: CONNECT BY loop in user data
      --为了欺骗它,这里用了一个PRIOR DBMS_RANDOM.VALUE, 因为DBMS_RANDOM.VALUE每次调用都返回不同结果,所以它认为两行数据不一样,所以不报错了。
      and prior dbms_random.value is not null
      ) ss--3,4,5
)ss where guid = guidname group by guid;
 --直接返回
 return pwtlxname;
end GetWtlxname;
© 版权声明 文章版权归作者所有,若需转载,请在显著位置标志该文章地址。
原文地址:https://www.cnblogs.com/luchenglong/p/13666984.html