【问题标题】:Create a copy of table and provide constraints to it while creating创建表的副本并在创建时为其提供约束
【发布时间】:2019-04-04 17:09:34
【问题描述】:

我是 Oracle 数据库的新手。我知道我们可以使用创建表的副本 CREATE TABLE copy_emp(eid, ename,job,mid,sal,dept_id) as SELECT employee_id, concat(first_name,last_name),job_id,manager_id,salary,department_id FROM employees; 稍后我们可以使用 alter table copy_emp add constraint epk FORIEGN KEY(dept_id) references departments(dept_id) 添加外键约束

但是是否可以在通过查询创建表副本时提供约束。

例如我们可以这样做:

CREATE table copy_emp(eid, ename,job,mid,sal,dept_id constraint dpt_fk references copy_dept(department_id) ON DELETEcascade)
as
SELECT employee_id,
concat(first_name,last_name),job_id,manager_id,salary,department_id 
FROM employees;

如果是,我们能否在创建表副本时提供约束,如果是,那么查询是什么,如果不是,为什么?

【问题讨论】:

标签: sql database oracle copy constraints


【解决方案1】:

不,你不能那样做;你的第二个语句(稍微固定)将得到

ORA-02440: Create as select with referential constraints not allowed
02440. 00000 -  "Create as select with referential constraints not allowed"
*Cause:    create table foo (... ref. con. ...) as select ...;
*Action:   Create the table as select, then alter the table to add the
           constraints afterwards.

这是提到in the documentation

对表的定义查询的限制

表查询受以下限制:

  • 表中的列数必须等于子查询中的表达式数。

  • 列定义只能指定列名、默认值和完整性约束,不能指定数据类型。

  • 您不能在包含AS subqueryCREATE TABLE 语句中定义外键约束,除非表是引用分区的并且该约束是表的分区引用约束。在所有其他情况下,您必须创建没有约束的表,然后稍后使用ALTER TABLE 语句添加它。

可以提供其他约束,如评论中链接到的答案@Jeff,因此您可以添加主键:

CREATE table copy_emp(eid primary key, ename,job,mid,sal,dept_id)
as
SELECT employee_id,
concat(first_name,last_name),job_id,manager_id,salary,department_id 
FROM employees;

或(只要约束名称是唯一的)

CREATE table copy_emp(eid, ename,job,mid,sal,dept_id,
  constraint emp_pk primary key (eid))
as
SELECT employee_id,
concat(first_name,last_name),job_id,manager_id,salary,department_id 
FROM employees;

【讨论】:

    猜你喜欢
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多