Search code examples
sqloracle-databaseoracle11gtalend

How to get column names from a query?


I have a specific query with joins and aliases, and I need to retrieve columns name for a REST request in Talend.

I'm using Talend Open Studio for Data Integration 6.2 and I've got an Oracle 11g database with a read-only account. I can execute scripts with Talend, For example the query:

select 
    u.name as "user", 
    f.name as "food", 
    e.rate 
from 
    Users as u 
    join Eval as e on u.user_id = e.user_id 
    join Food as f on e.food_id = f.food_id
where
    1 = 1

should give the following result:

+------+--------+------+
| user | food   | rate |
+------+--------+------+
| Baba | Donuts | 16.0 |
| Baba | Cheese | 20.0 |
| Keke | Pasta  | 12.5 |
| Keke | Cheese | 15.0 |
+------+--------+------+

And I try to get the columns (in the right order) as follows by using scripts or Talend:

+--------+
| Column |
+--------+
| user   |
| food   |
| rate   |
+--------+

Is there a way to query the Oracle database to get the columns or using talend to retrieve them?

UPDATE

Thanks to Marmite Bomber, a duplicate has been identified here for the Oracle approach. Now we need a Talend approach to the problem.


Solution

  • You can try this on a tJavaRow, following your DBInput component :

    for (java.lang.reflect.Field field: row1.getClass().getDeclaredFields()) {
    context.columnName = field.getName();
          System.out.println("Field name is " + context.columnName );      
               }
    

    Spotted on talend help center here : https://community.talend.com/t5/Design-and-Development/resolved-how-to-get-the-column-names-in-a-data-flow/td-p/99172

    You can extend this, and put the column list on your outputflow :

    //add this inside the loop, and 'columnNames' as an output row in tJavaRow schema
    
                 output_row.columnNames+=context.columnName+";";
    

    With a tNormalize after tJavaRow, you shoud get the expected result.