0

I have two tables. Lets say tab1 and tab2.

tab1 has data like this:

ID Field Name
00001 col1
00001 col63
00002 col3
00002 col47
00003 col22
00003 col40

Each ID has always 2 Field Name values.

And tab2 has columns col1,col2,col3,col4....col70

I want to select columns dynamically from tab2.

Like for 00001 it should be:

select col1,col63 from tab2;

Similarly for 00002 it should be :

select col3,col47 from tab2;

Is there any way to achieve this without using function or procedure ? I am using Oracle 11G.

1
  • 2
    case field_name when 'col1' then col1 when 'col2' then col2.... Or in Oracle fashion: decode(field_name, 'col1', col1, 'col2', col2, 'col3', col3) no dynamic SQL and its vulnerability Commented Jul 28, 2021 at 20:55

1 Answer 1

2

Assuming that the columns have compatible types, then you can do what you want by using case expressions:

select (case when t1.field1 = 'col1' then col1
             when t1.field1 = 'col2' then col2
             when t1.field1 = 'col3' then col3
             when t1.field1 = 'col4' then col4
        end),
       (case when t1.field2 = 'col1' then col1
             when t1.field2 = 'col2' then col2
             when t1.field2 = 'col3' then col3
             when t1.field2 = 'col4' then col4
        end)
from tab2 join
     (select id, min(fieldname) as field1, max(fieldname) as field2
      from t1
      group by id
     ) t1
     on t1.id = t2.id
Sign up to request clarification or add additional context in comments.

5 Comments

the solution is great. but one thing , the tab2 has at least 70 columns, and the field name of tab1 may vary from col1 to col70.
@SayandipGhatak Then write 70 terms in the CASE statement.
Isn't there any solution like this : select (select listagg(fieldname,',') from tab1 where id = '00001') from tab2
@SayandipGhatak SQL is a static language. Optimizer needs to built the execution plan, obviously, before the execution. How can it do this without column names?
@SayandipGhatak . . . You can generate the code using a SQL query or spreadsheet.

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.