Oracle drop table if exists 从第 1 行开始抛出错误:在命令中

Oracle drop table if exists is throwing an error starting at line 1: in command

我们试图删除数据库中的所有表,然后重新创建它们,但是 oracle 抛出错误。错误报告是:

Error report -
ORA-06550: line 12, column 1:
PLS-00103: Encountered the symbol "CREATE" 
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

代码是:

BEGIN
   EXECUTE IMMEDIATE 'DROP TABLE ' || EMPLOYEE;
   EXECUTE IMMEDIATE 'DROP TABLE ' || ADDRESS;

EXCEPTION
   WHEN OTHERS THEN
      IF SQLCODE != -942 THEN
         RAISE;
      END IF;
END;

CREATE TABLE EMPLOYEE(
    EmployeeID int,
    FirstName varchar(225),
    LastName varchar(255),
    Position varchar(255),
    SSN int,
    Address varchar(255),
    Phone int,
    AddressID int,
    
    PRIMARY KEY (EmployeeID),
    FOREIGN KEY (AddressID) REFERENCES ADDRESS(AddressID)
);

CREATE TABLE ADDRESS(
    AddressID int,
    Street varchar(225),
    City varchar(225),
    State varchar(225),
    Zip int
);

我们想对所有表执行此操作,但到目前为止它不适用于我们在开始时尝试删除的两个表。

尝试交换 CREATE 表,因为您尝试使用在创建时无法访问的外键 (AddressID)。

CREATE TABLE ADDRESS(
...

CREATE TABLE EMPLOYEE(
...

应该是这样的:

SQL> BEGIN
  2      BEGIN
  3          EXECUTE IMMEDIATE 'DROP TABLE EMPLOYEE';
  4      EXCEPTION
  5          WHEN OTHERS THEN
  6              IF sqlcode != -942 THEN
  7                  RAISE;
  8              END IF;
  9      END;
 10
 11      BEGIN
 12          EXECUTE IMMEDIATE 'DROP TABLE ADDRESS';
 13      EXCEPTION
 14          WHEN OTHERS THEN
 15              IF sqlcode != -942 THEN
 16                  RAISE;
 17              END IF;
 18      END;
 19
 20  END;
 21  /

PL/SQL procedure successfully completed.

SQL> CREATE TABLE ADDRESS(
  2      AddressID int primary key,
  3      Street varchar(225),
  4      City varchar(225),
  5      State varchar(225),
  6      Zip int
  7  );

Table created.

SQL> CREATE TABLE EMPLOYEE(
  2      EmployeeID int,
  3      FirstName varchar(225),
  4      LastName varchar(255),
  5      Position varchar(255),
  6      SSN int,
  7      Address varchar(255),
  8      Phone int,
  9      AddressID int,
 10      PRIMARY KEY (EmployeeID),
 11      FOREIGN KEY (AddressID) REFERENCES ADDRESS(AddressID)
 12  );

Table created.

SQL>

你做错了什么?

  • table 名称应该用动态 SQL 括在单引号中,因为 - 如果它们不存在,代码将失败
  • 将每个动态 SQL 语句包含在它自己的 BEGIN-EXCEPTION-END 块中以避免 table 之一存在(而另一个不存在)时出现问题
  • 用斜杠终止 PL/SQL 块(第 11 行);否则,某些工具(如 SQL*Plus)将无法将整个代码作为 script
  • 执行
  • 首先创建 ADDRESS table(并添加主键约束,否则 EMPLOYEE 上的外键将失败)