简体   繁体   中英

How to handle invalid_identifier exception in pl/sql?

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:

  • You declare a user-defined exception.
  • You associate the exception with the Oracle error thrown on an unknown column identifier, whose code is 00904 .
  • The sql query is executed as native dynamic sql - otherwise the code wouldn't compile in the first place.
  • The error message is composed from the text of your choice complemented by the offending column name. This name is extracted from the oracle error message by means of a regular expression. Note that this example hasn't been tested for the case of multiple offending names - however, you should get the drift.
  • The second line of output produces the original error message and is contained for illustrative purposes only.
  • The exception handler responds to your exception only and re-raises any other exception to be handled in one of the surrounding blocks.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM