Skip to Main Content
  • Questions
  • How can I determine the underlying expression for a given view name/column alias in a query?

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Glenn.

Asked: June 23, 2021 - 1:44 pm UTC

Last updated: June 24, 2021 - 8:10 am UTC

Version: Oracle 12c

Viewed 1000+ times

You Asked

I have several hundred views that contain column aliases in their definitions. I need to programmatically (preferably SQL query) determine the underlying expression for a given column alias, but I can't find any views or tables in Oracle that correlate the alias with the expression. DBA_VIEWS.TEXT doesn't include the aliases. DBMS_METADATA.GET_DDL will generate the alias list in the view-definition header, but those are positional, comma-separated values that do not directly correlate to the expressions to which they apply. The correlation has to exist somewhere in the database since GET_DDL can find both the alias and the expression to generation the view definition. How can I determine the underlying expression for a given view name/column alias in a query?

Thanks

and Chris said...

You can use dbms_utility.expand_sql_text to extract the full query. If you have views on views, this resolves to the base tables.

For example:

create table t (
  c1 int, c2 int
);

create or replace view vw  as 
  select c1, c2, c1 + c2 as sm from t;
  
create or replace view vw2 ( c1, c2, c3 ) as 
  select * from vw;

declare
  l_clob clob;
begin
  dbms_utility.expand_sql_text (
    input_sql_text  => q'!select * from vw2!',
    output_sql_text => l_clob  );
  dbms_output.put_line(l_clob);
end;
/

select "A1"."C1"    "C1",
       "A1"."C2"    "C2",
       "A1"."C3"    "C3"
from (
  select "A2"."C1"    "C1",
         "A2"."C2"    "C2",
         "A2"."SM"    "C3"
  from (
    select "A3"."C1"                  "C1",
           "A3"."C2"                  "C2",
           "A3"."C1" + "A3"."C2"      "SM"
    from "CHRIS"."T" "A3"
  ) "A2"
) "A1"


As this shows, extracting the underlying expression can still be a challenge if it's been re-aliased to another name at some point. I'm not aware of another method which will show you the full query.

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Glenn Blackshear, June 24, 2021 - 2:16 pm UTC

Thanks for your response. Not quite was I was after, but it got me much closer than I was. I had been checking in system tables/views. i hadn't thought about a system package/function to provide the code. Now I have full code available to parse.

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.