创建表时出现约束错误:"此处不允许使用约束规范"

时间:2016-04-22 13:09:24

标签: sql oracle constraints

我试图声明funtom_customer表是funtom_employee表的外键...

create table Funtom_customer
(
    cust_ID         number(3) constraint cust_ID primary key,
    cust_Name       varchar2(50) constraint cust_Name not null,
    cust_Contact    varchar2(50),   
    cust_Acmanager  number(3) 
         CONSTRAINT cust_Acmanager FOREIGN KEY (funtom_employee),
    cust_Addr1      varchar2(50),
    cust_Addr2      varchar2(50),
    cust_Addr3      varchar2(50),
    cust_Addrpc     varchar2(10)
);

2 个答案:

答案 0 :(得分:1)

您的语法在几个方面都是格式错误的。假设funtom_employee表中的主键称为emp_id,您可以在线定义约束:

create table funtom_customer
(
  cust_id         number(3) primary key,
  cust_name       varchar2(50) not null,
  cust_contact    varchar2(50), 
  cust_acmanager  number(3) references funtom_employee (emp_id),
  cust_addr1      varchar2(50),
  cust_addr2      varchar2(50),
  cust_addr3      varchar2(50),
  cust_addrpc     varchar2(10)
);

...这将导致系统生成约束名称,或指定外联作为命名约束:

create table funtom_customer
(
  cust_id         number(3),
  cust_name       varchar2(50) not null,
  cust_contact    varchar2(50), 
  cust_acmanager  number(3),
  cust_addr1      varchar2(50),
  cust_addr2      varchar2(50),
  cust_addr3      varchar2(50),
  cust_addrpc     varchar2(10),
  constraint pk_funtom_customer primary key (cust_id),
  constraint fk_funtom_customer_acmanager foreign key (cust_acmanager)
    references funtom_employee (emp_id)
);

您也可以创建表格并在之后添加约束,如@Thomas所示。

你可以命名一个非空约束,但它不常见;您还可以使用一个命名约束来检查列是否为空,但是它不会在数据字典中显示为不可为空(例如,当您描述该表时)。

答案 1 :(得分:0)

create table Funtom_customer
(
cust_ID       number(3) not null,
cust_Name     varchar2(50) not null,
cust_Contact      varchar2(50), 
cust_Acmanager    number(3)   ,
cust_Addr1    varchar2(50),
cust_Addr2    varchar2(50),
cust_Addr3    varchar2(50),
cust_Addrpc   varchar2(10)
)
;


alter table Funtom_customer add constraint pk_cust_ID  primary key (cust_ID);
alter table Funtom_customer add constraint fk_cust_Acmanager foreign key (cust_Acmanager) references funtom_employee(referenced_col);