There is one table, let us say VW_RESULT like below:
ID
Quarter
Risk
00001
Q0
2
00001
Q1
3
00001
Q2
1
00001
Q3
1
00001
Q4
2
Now I have to show the column names in the 1st row.
I want output like this:
Col1
Col2
Col3
ID
Quarter
Risk
00001
Q0
2
00001
Q1
3
00001
Q2
1
00001
Q3
1
00001
Q4
2
I can easily achieve this if the number of columns is fixed, using UNION ALL
.
But the number of columns will vary from time to time.
I want to make this dynamic so that I don't have to put column names manually.
I am using Oracle 11g .
Take your columns in variable and concatenate all columns you are getting at every run..execute your with execute immediate and concatenate your variable with the statement as well
To achieve your requirement, all your datatype should be string as all the columns are strings. In case if any of your datatype is other than string it will not work. Eg: ID column seems to be integer datatype, if you are trying to merge 'ID' string into ID column, according to SQL standard, it will fail. However below is the solution if all the columns in the respective table is in string format.
declare
v_Sql1 varchar(1000);
v_Sql2 varchar(1000);
begin
select (LISTAGG(chr(39)||column_name||chr(39), ',') WITHIN GROUP (ORDER BY
column_id)) into v_Sql1 from cols where table_name = 'VW_RESULT';
v_Sql2:= 'select * from
(select column_name from cols where table_name = ''VW_RESULT'')
pivot
(
max(column_name)
for column_name in (' || v_Sql1 || '))
union select * from VW_RESULT';
dbms_output.put_line(v_Sql1);
dbms_output.put_line(v_Sql2);
execute immediate v_Sql2;
end;
/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.