i need to check if a certain SELECT statement includes a field (column) that doesn't exists in a table, for example:
select col1, col2, col3 from table1
if col1 dosen't exists i want to show "missing field", instead for the user to get an invalid identifier error.
what is my best and short option to do this?
This code fragment should get you started:
set serveroutput on
DECLARE
exc_invalid_id EXCEPTION;
PRAGMA EXCEPTION_INIT(exc_invalid_id, -904);
l_message VARCHAR2(4000);
BEGIN
EXECUTE IMMEDIATE '
SELECT col1
, col2
, col3
FROM table1
';
EXCEPTION
WHEN exc_invalid_id THEN
l_message := regexp_replace(sqlerrm, '^[A-Z]{3}-[0-9]{5}: "([^"]+)".*$', '\1');
dbms_output.put_line ( 'missing field '''||l_message||'''');
dbms_output.put_line ( 'exception: sqlcode='||SQLCODE||', sqlerrm='''||sqlerrm||'''');
WHEN OTHERS THEN
RAISE;
END;
/
show errors
Explanation:
00904
. Try:
select 1
from user_tab_columns
where table_name = '<your table name>' and
column_name = '<your column name>'
That will only work for tables in the same schema. Replace with ALL_TAB_COLUMNS view if you need other schemas. If no row is returned, then no column exists. I am assuming this is for dynamic SQL, since for static SQL you will get a compile error if the column is missing anyways.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.