Is there any setting or method I can use to get Oracle to return results in <table>.<column> format? For example:
Query:
SELECT *
FROM foo f
INNER JOIN bar b
ON b.foo_id = f.id
Desired results:
F.ID F.BLAH B.ID B.FOO_ID B.BLAH
--------------------------------------------------------
1 blah 7 1 blah
2 blah 8 2 blah
3 blah 9 2 blah
The obvious solution is to individually alias each column SELECT f.id AS F_ID, ...; however, I’m needing to export some very large legacy tables (300+ columns), so using this method would cause the queries to be enormous and impractical.
There is no “option” in Oracle to do this; you may be able to find a client that allows you to do so as this is a job that would normally be done in the client; I don’t know of one.
To expand upon tbone’s answer you’re going to have to do this dynamically. This does not mean that you have to list every column. You would use the data dictionary, specifically all_tab_columns or
user_tab_columnsto create your query. It would be easier to create a view with the exact definition you want so that you can re-use it if you want.The aim is to use the fact that the columns existence is stored in a table as a string in order to create a query to use that column. As the column names and table names are stored as strings you can use string aggregation techniques to easily create a query or DDL statement that you can then manually, or dynamically, execute.
If you’re using Oracle 11g Release 2 the
listaggfunction is available to help you:Assuming this table structure:
This single query produces the following:
and here’s a SQL Fiddle to prove it.
In you’re not using 11.2 you can achieve exactly the same results using the undocumented function
wm_concator the user-defined functionstragg, which was created by Tom Kyte. Oracle Base has an article on string aggregation techniques and there are many posts on Stack Overflow.As a little addendum you can actually create exactly what you’re looking for with a small change to the above query. You can use a quoted identifier to create a column in the
TABLE_NAME.COLUMN_NAMEformat. You have to quote it as.is not a valid character for an object name in Oracle. The benefit of this is that you gain exactly what you want. The downside is that querying the created view is a huge pain if you don’t useselect * from ...; selecting named columns will require them to be quoted.This query returns: