Oracle 行列转换

1.  列转行

使用Oracle提供的功能函数,wm_concat, 但要注意,使用该函数转换出来的值是blob类型,需要手动转换成char类型;

代码如下:

to_char(wm_concat(column))
-- 竖杠为分隔符
select replace(wm_concat(name),',','|') from test;

  

2. 行转列

Oracle本身没有提供行转列功能,需要自己实现,下面是解析使用逗号隔开的字符串转换成列的示例:

-- 定义返回类型
create or replace type acc_type as object
(acc varchar2(50))
/

create or replace type acc_table as table of acc_type
/

create or replace function str2table (acc_str in varchar2) return acc_table pipelined
is
v_str varchar2(30000) := acc_str;
v_acc varchar2(30);
v_acc_end pls_integer;
begin
loop
v_acc_end := instrb(v_str,',');
exit when (v_acc_end=0 or v_str is null);
v_acc := substrb(v_str,1,v_acc_end-1);
v_str := ltrim(v_str,v_acc);
v_str := ltrim(v_str,',');
pipe row(acc_type(rtrim(v_acc,';')));
end loop;
return;
end;
/

  

原文地址:https://www.cnblogs.com/fubinhnust/p/9925973.html