Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alias all column in a query with a prefix

it's possible to alias all column with a prefix, in a select? I have a group of tables in an Oracle db that I need to join together, and most of them have the same column names. I would like to have something like

select MAGIC_ADD_PREFIX("PREFIX", *) from TABLE

and have a result like

+---------+----------+----------+
|PREFIX_ID|PREFIX_FOO|PREFIX_BAR|
+---------+----------+----------+
|...      |          |          |

ATM the only thing I can think is something chumsky like

select ID PREFIX_ID, FOO PREFIX_FOO, BAR PREFIX_BAR from TABLE

but it's ugly as hell and error-prone

==== further explanation ====

The problem with

select TABLE.*,...

is that I'm using java + jdbc drivers to retrieve the columns, and the java.sql.ResultSet methods (resultset.getInt("COLUMNNAME"), .getString("COLUMNNAME")...) doesn't support the syntax "TABLENAME.COLUMNAME".

if I do (simplified, no error cheks...)

ResultSet rs = mkResultSet("select * from table_a, table_b");
rs.next();
System.out.println(rs.getInt("table_a.id"));

I get a SQLException with invalid column name as message

like image 379
Vito De Tullio Avatar asked Mar 23 '10 15:03

Vito De Tullio


People also ask

How do I give an alias to multiple columns in SQL?

You can alias an expression or column, such as in select u.id as user_id and select upper(u. username) as uppercase_name , and you can alias a table as in from users u . There exists no group alias for multiple columns.

How do I specify a column alias in SQL?

The basic syntax of a table alias is as follows. SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition]; The basic syntax of a column alias is as follows.

How do I give an alias a column name?

You can declare an alias for any column in the select list of the Projection clause. The GROUP BY clause can reference the column by its alias. This temporary name is in scope only while the SELECT statement is executing.

Can you use column alias in SELECT statement?

Column aliases can be used in the SELECT list of a SQL query in PostgreSQL. Like all objects, aliases will be in lowercase by default.


1 Answers

You can do

select a.*, b.* from table_a a, table_b b where.....

Or you could create views over the base tables like

   create view a_vw as select a.col1 a_col1, a.col2 a_col2...

You could generate the SQL for creating a_vw fairly easily from selecting the column name from user_tab_columns

like image 67
Gary Myers Avatar answered Oct 02 '22 14:10

Gary Myers