日期:2014-05-17  浏览次数:20863 次

再发 行转列通用过程
本帖最后由 wildwave 于 2010-01-20 20:17:41 编辑
之前发过一个帖子,叫行转列的通用过程,http://topic.csdn.net/u/20091019/11/67cd55a3-3f42-4db7-a3f8-91dd52a913cd.html能满足最基本的需求。但也有一些缺陷,现在对其进行完善
代码

1.使用视图
create or replace procedure row_to_col(tabname in varchar2,
                                  group_col in varchar2,
                                  column_col in varchar2,
                                  value_col in varchar2,
                                  Aggregate_func in varchar2 default 'max',
                                  colorder in varchar2 default null,
                                  roworder in varchar2 default null,
                                  when_value_null in varchar2 default null,
                                  viewname in varchar2 default 'v_tmp')
Authid Current_User
as
  sqlstr varchar2(2000):='create or replace view '||viewname||' as select '||group_col||' ';
  c1 sys_refcursor;
  v1 varchar2(100);
begin
  open c1 for 'select distinct '||column_col||' from '||tabname||case when colorder is not null then ' order by '||colorder end;
  loop
    fetch c1 into v1;
    exit when c1%notfound;
    sqlstr:=sqlstr||chr(10)||','||case when when_value_null is not null then 'nvl(' end||
      Aggregate_func||'(decode(to_char('||column_col||'),'''||v1||''','||value_col||'))'||
      case when when_value_null is not null then chr(44) ||when_value_null||chr(41) end||'"'||v1||'"';
  end loop;
  close c1;
  sqlstr:=sqlstr||' from '||tabname||' group by '||group_col||case when roworder is not null then ' order by '||roworder end;
  execute immediate sqlstr;
end row_to_col