要求解释这个PL / SQL代码

时间:2015-02-11 12:43:30

标签: sql oracle plsql

我想问你这个PL / SQL代码究竟在做什么:

DECLARE
   table_doesnot_exists   EXCEPTION;
   PRAGMA EXCEPTION_INIT (table_doesnot_exists, -942);
BEGIN
   EXECUTE IMMEDIATE 'DROP TABLE TABLE_NAME';
EXCEPTION
   WHEN table_doesnot_exists
   THEN NULL;
END;

我部分理解这一点,但我对此-942感到好奇。

3 个答案:

答案 0 :(得分:4)

这只是表的oracle异常代码不存在

来自oracle文档:

ORA-00942 table or view does not exist

Cause: The table or view entered does not exist, a synonym that is not allowed here was used, or a view was referenced where a table is required. Existing user tables and views can be listed by querying the data dictionary. Certain privileges may be required to access the table. If an application returned this message, the table the application tried to access does not exist in the database, or the application does not have access to it.

了解更多信息http://www.techonthenet.com/oracle/errors/ora00942.php

答案 1 :(得分:4)

我已经通过并评论了该块。基本上,您的代码会测试自定义错误处理。

DECLARE
  --Define the custom exception
  table_doesnot_exists   EXCEPTION;
  /*
   *In order to use the custom exception we have to declare it (typically used with ORA messages
   *that have no predefined name. Syntax: PRAGMA EXCEPTION_INIT (exception_name, -ORA_ERR_#);
   *In this case: 00942, 00000, "table or view does not exist"
   *Original code cited 942 but the oerr code is actually 00942, the leading 0's in this case are irrelevant
   */
  PRAGMA EXCEPTION_INIT (table_doesnot_exists, -942);
BEGIN
  --Attempt to drop the table
  EXECUTE IMMEDIATE 'DROP TABLE test_table_does_not_exist';
EXCEPTION
  --If the table we attempted does not exist then our custom exception will catch the ORA-00942
  WHEN table_doesnot_exists
  --Now lets throw out a debug output line
  THEN DBMS_OUTPUT.PUT_LINE('table does not exist');
END;
/

答案 2 :(得分:0)

它删除表,如果在尝试删除它时表不存在,它会捕获相应的错误(EXCEPTION_INIT Pragma 中的 ORA-00942 = -942)然后什么都不做。

如果您在另一个 RDBMS(例如 Postgres)上,您最好使用“DROP TABLE IF EXISTS my_table”,但遗憾的是 Oracle 不提供这种语法。