Oracle-11g
如何在 PL/SQL 中執行這個過程?
我有以下格式的表格:
Persnbr | Userfieldcd | Value 01 | Port | Funds 01 | Vip1 | Systems 02 | Port | Bank 02 | Vip1 | Authority
這就是我想要的:
Persnbr | Port | Vip1 01 | Funds | Systems 02 | Bank | Authority
由於我不知道 userfieldcd 列中的所有欄位,我正在嘗試動態旋轉表格。所以我正在使用這個過程,但我不知道如何在 PL/SQL 開發人員中呼叫它。我正在使用 Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
CREATE OR REPLACE procedure dynamic_pivot_po(p_cursor in out sys_refcursor) as sql_query varchar2(1000) := 'select persnbr '; begin for x in (select distinct userfieldcd from persuserfield order by 1) loop sql_query := sql_query || ' , min(case when userfieldcd = '''||x.userfieldcd||''' then value else null end) as '||x.userfieldcd; dbms_output.put_line(sql_query); end loop; sql_query := sql_query || ' from persuserfield group by persnbr order by persnbr'; dbms_output.put_line(sql_query); open p_cursor for sql_query; end; /
當我使用以下方法呼叫程序時:
VARIABLE x REFCURSOR BEGIN dynamic_pivot_po(:x) END /
它給了我
ORA-00900: 無效的 SQL 語句。
您可以使用 PIVOT 運算符完成此操作,但它需要對所有旋轉值進行硬編碼。
select * from (select Persnbr, Userfieldcd, value from pivot_test) pivot (max(value) for Userfieldcd in ('Port', 'Vip1'));
作為範例動態建構查詢:
declare in_clause varchar2(256); sel_query varchar2(256); n number := 0; begin for x in (select distinct userfieldcd from persuserfield) loop if n <> 0 then in_clause := in_clause || ', '; end if; in_clause := in_clause || '''' || x.userfieldcd || ''''; n := 1; end loop; sel_query := 'select * from (select Persnbr, userfieldcd, value from persuserfield) pivot (max(value) for userfieldcd in ('||in_clause||'));'; dbms_output.put_line (sel_query); end; /