I have a column in a table with simple sql queries and I want to regexp_substr the table name from them. Examples of texts:
SELECT PT.PT_PARTY_NAME VALUE,PT.PT_PARTY_NAME LABEL
FROM DWH_OWNER.DWH_ACCOUNTS ACC,
DWH_OWNER.DWH_PARTIES PT
WHERE ACC.ACC_SOURCE_ID = :P_DOMVAL_REF1
AND ACC.ACC_PT_KEY = PT.PT_KEY
or
SELECT DISTINCT QRMPT_PRODUCT VALUE, QRMPT_PRODUCT LABEL FROM
DWH_OWNER.DWH_QRM_PRODUCT_TYPES ORDER BY VALUE
So, I need to find the "FROM", skip some whitespaces then get the first word. I'm not interested for the moment in the second table.
What I've done:
select
sql,
regexp_substr(upper(sql), '(\s)FROM(\s)*([[:alnum:]]|\.|_)*') tablename
from my_table_with_queries;
Output:
FROM DWH_OWNER.DWH_ACCOUNTS
FROM
DWH_OWNER.DWH_QRM_PRODUCT_TYPES
What's wrong with my qyery: It outputs the tablename with the "FROM " before the table name. I want the table name directly, without whitespaces.
Desired output:
DWH_OWNER.DWH_ACCOUNTS
DWH_OWNER.DWH_QRM_PRODUCT_TYPES
EDIT:
I managed to do regexp_substr(tablename, '(\w|_|\.)+', 1,2)
over the previous step to do the tablename clean. But It is possible to get the desired output with a single regexp?
Here should be an sqlfiddle, but the site does not work in this moment. The query:
with a as (
select 'SELECT PT.PT_PARTY_NAME VALUE,PT.PT_PARTY_NAME LABEL
FROM DWH_OWNER.DWH_ACCOUNTS ACC,
DWH_OWNER.DWH_PARTIES PT
WHERE ACC.ACC_SOURCE_ID = :P_DOMVAL_REF1
AND ACC.ACC_PT_KEY = PT.PT_KEY' sql from dual
union all
select 'SELECT DISTINCT QRMPT_PRODUCT VALUE, QRMPT_PRODUCT LABEL FROM
DWH_OWNER.DWH_QRM_PRODUCT_TYPES ORDER BY VALUE' from dual
)
select
regexp_substr(upper(sql), '\sFROM\s*(\w|\.|_)*') tablename, sql
from a;