0

I am using this code to output some table data.

select uID, ColumnName, ColumnResult
from TABLE
unpivot
(
ColumnResult
for ColumnName in (COL1,COL2,COL3)
)u

My problem is I have to type in every column and some of my tables have 100+ rows. This can be very tedious to write every column (Col1,Col2,Col3, etc). Is there a way to dynamically get all the column names and put them inside the 'IN'statement?

4

1 回答 1

1

您可以创建一个过程来生成将执行的 sql 字符串。这是一个示例解决方案:

CREATE OR REPLACE procedure dynamic_unpivot(p_cursor in out sys_refcursor)
as
    sql_query varchar2(1000) := 'select id, columnName, columnResult 
                                               from yourtable ';

    sql_unpiv varchar2(50) := null;

    begin
        for x in (select t.column_name ls 
                    from user_tab_columns t
                    where t.table_name = 'YOURTABLE'
                        and t.column_name not in ('ID'))
        loop
            sql_unpiv := sql_unpiv ||
                '  '||x.ls||' ,';

                dbms_output.put_line(sql_unpiv);
        end loop;

        sql_query := sql_query || 'unpivot
                                               (
                                                    columnResult
                                                    for columnName in ('||substr(sql_unpiv, 1, length(sql_unpiv)-1)||')
                                                )';
        dbms_output.put_line(sql_query);

        open p_cursor for sql_query;
    end;
/

然后您可以使用以下命令执行结果(我的示例来自 TOAD):

variable x refcursor
exec dynamic_unpivot(:x)
print x;
于 2013-04-30T21:45:01.353 回答