dynamicOracle Pivot_In_Clause

我有点卡住了 我想做一个用户angular色关系数据透视表,我的查询到目前为止是这样的:

WITH PIVOT_DATA AS ( SELECT * FROM ( SELECT USERNAME, GRANTED_ROLE FROM DBA_USERS@DB_LINK U LEFT OUTER JOIN DBA_ROLE_PRIVS@DB_LINK R ON U.USERNAME = R.GRANTEE ) ) SELECT * FROM PIVOT_DATA PIVOT ( COUNT(GRANTED_ROLE) FOR GRANTED_ROLE IN('CONNECT') -- Just an example ) ORDER BY USERNAME ASC; 

它工作得很好,做这个工作,但我不想写任何我想在pivot_in_clausesearch的pivot_in_clause ,因为我们得到了他们吨,我不想每次检查是否有任何变化。

那么有没有办法在pivot_in_clause写入一个SELECT ? 我自己试了一下:

 [...] PIVOT ( COUNT(GRANTED_ROLE) FOR GRANTED_ROLE IN( SELECT ROLE FROM DBA_ROLES@DB_LINK ) ) [...] 

但它总是给我一个ORA-00936:整个查询的第一行中的“缺失的expression”,我不知道为什么。 在pivot_in_clause不能有一个SELECT ,或者我做错了吗?

你可以在脚本中build立dynamic查询,看看这个例子:

 variable rr refcursor declare bb varchar2(4000); cc varchar2( 30000 ); begin WITH PIVOT_DATA AS ( SELECT * FROM ( SELECT USERNAME, GRANTED_ROLE FROM DBA_USERS U LEFT OUTER JOIN DBA_ROLE_PRIVS R ON U.USERNAME = R.GRANTEE ) ) select ''''|| listagg( granted_role, ''',''' ) within group( order by granted_role ) || '''' as x into bb from ( select distinct granted_role from pivot_data ) ; cc := q'[ WITH PIVOT_DATA AS ( SELECT * FROM ( SELECT USERNAME, GRANTED_ROLE FROM DBA_USERS U LEFT OUTER JOIN DBA_ROLE_PRIVS R ON U.USERNAME = R.GRANTEE ) ) SELECT * FROM PIVOT_DATA PIVOT ( COUNT(GRANTED_ROLE) FOR GRANTED_ROLE IN(]' || bb || q'[) -- Just an example ) ORDER BY USERNAME ASC]'; open :rr for cc; end; / SET PAGESIZE 200 SET LINESIZE 16000 print :rr 

这是结果(只有小片段,因为它非常宽,很长)

 ----------------------------------------------------------------------------------------------------------------------------------- USERNAME 'ADM_PARALLEL_EXECUTE_TASK' 'APEX_ADMINISTRATOR_ROLE' 'AQ_ADMINISTRATOR_ROLE' 'AQ_USER_ROLE' ------------------------------ --------------------------- ------------------------- ----------------------- ---------------------- ANONYMOUS 0 0 0 0 APEX_030200 0 0 0 0 APEX_PUBLIC_USER 0 0 0 0 APPQOSSYS 0 0 0 0 .............. IX 0 0 1 1 OWBSYS 0 0 1 1