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?

1
  • Redgate has very good plugin for SQL Server red-gate.com/products/sql-development/sql-prompt they do have some plugins for Oracle but not sure if they have like SQL prompt, you can check with them. Commented Apr 30, 2013 at 21:10

1 Answer 1

1

You could create a procedure that generates the sql string that would then be executed. Here is a sample solution:

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;
/

Then you could use the following to execute the result (my sample is from TOAD):

variable x refcursor
exec dynamic_unpivot(:x)
print x;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.