This still cannot be done with 100% native SQL. These overly-dynamic situations are usually best avoided; a little extra typing is generally better than adding
complicated code.
If you truly have an exceptional case and are willing to pay the price there is a way to do this. It doesn't use 100% natural SQL, but it could be considered "pure" SQL since it uses the Oracle Data Cartridge framework to extend the database.
You can use my open source project Method4 to run dynamic SQL in SQL. Follow the Github steps to download and install the objects. The code is painfully complicated but luckily you won't need to understand most of it. Only the simple changes below are necessary to get started on customizing column names.
Method4 Changes
Create a variable to hold the new column name. Add it to the declaration section of the function ODCITableDescribe, on line 12 of the file METHOD4_OT.TPB.
v_new_column_name varchar2(32);
Create a SQL statement to map the old column to the new column. Add this to line 31, where it will be run for each column.
--Get mapped column name if it exists. If none, use the existing name.
select nvl(max(target_column_name), r_sql.description(i).col_name)
into v_new_column_name
from column_names
where source_column_name = r_sql.description(i).col_name;
Change line 42 to refer to the new variable name:
substr(v_new_column_name, 1, 30),
Mapping Table
drop table column_names;
create table column_names
(
source_column_name varchar2(30),
target_column_name varchar2(30),
constraint column_names_pk primary key(source_column_name)
);
insert into column_names values('A1234', 'BETTER_COLUMN_NAME');
insert into column_names values('B4321', 'Case sensitive column name.');
Query Example
Now the column names from any query can magically change to whatever values you want. And this doesn't simply use text replacement; the columns from a *
will also change.
SQL> select * from table(method4.query('select 1 a1234, 2 b4321, 3 c from dual'));
BETTER_COLUMN_NAME Case sensitive column name. C
------------------ --------------------------- ----------
1 2 3
Warnings
Oracle SQL is horrendously complicated and any attempt to build a layer on top if it has many potential problems. For example, performance will certainly be slower. Although I've created many unit tests I'm sure there are some weird data types that won't work correctly. (But if you find any, please create a Github issue so I can fix it.)
In my experience, when people ask for this type of dynamic behavior, it's usually not worth the cost. Sometimes a little extra typing is the best solution.