我正在尝试创建一个表,但它没有被创建。问题在于限制。主要是NOT NULL和FOREIGN KEY

时间:2014-11-17 18:18:06

标签: sql oracle ora-00904

CREATE TABLE Customer(
Cust_Id Number(4),
Cust_First_Name  VarChar2(20),
Cust_Mid_Name VarChar2(20),
Cust_Last_Name VarChar2(20),            
Account_Type Varchar2(15),          
Cust_Email VarChar2(30),                
Cust_Mobile Number(10),
Bank_Id NUMBER(4),
Account_No Number(4),
CONSTRAINT Cust_Id_Pri_Key PRIMARY KEY (Cust_Id),
CONSTRAINT Cust_Last_Name_Not_Null NOT NULL (Cust_Last_Name),
CONSTRAINT Cust_First_Name_Not_Null NOT NULL (Cust_First_Name),
CONSTRAINT Cust_Email_Unq UNIQUE(Cust_Email),
CONSTRAINT Cust_Mobile_Unq UNIQUE(Cust_Mobile),
CONSTRAINT Bank_Id_For_Key FOREIGN KEY REFERENCES bank(bankId)
);

2 个答案:

答案 0 :(得分:2)

使用SQL小提琴:http://sqlfiddle.com/#!4/05311

以下是SQL的外观。

CREATE TABLE Customer(
Cust_Id Number(4) NOT NULL,
Cust_First_Name  VarChar2(20) NOT NULL,
Cust_Mid_Name VarChar2(20),
Cust_Last_Name VarChar2(20) NOT NULL,            
Account_Type Varchar2(15),          
Cust_Email VarChar2(30),                
Cust_Mobile Number(10),
Bank_Id NUMBER(4),
Account_No Number(4),
CONSTRAINT Cust_Id_Pri_Key PRIMARY KEY (Cust_Id),
CONSTRAINT Cust_Email_Unq UNIQUE(Cust_Email),
CONSTRAINT Cust_Mobile_Unq UNIQUE(Cust_Mobile),
CONSTRAINT Bank_Id_For_Key FOREIGN KEY (Bank_Id) REFERENCES bank(bankId)  
);

几乎所有错误都来自语法。

  • NOT NULL在列名称中指定,而不是单独的约束。
  • FOREIGN KEY CONSTRAINT requires you to specify the source column name, and the FOREIGN KEY column in the table that it is defined as a PRIMARY KEY`

答案 1 :(得分:0)

您有两个问题:您无法将NOT NULL指定为外联约束,并且您在外键约束中缺少列名。以下应该有效:

CREATE TABLE customer
(
   cust_id NUMBER (4),
   cust_first_name VARCHAR2 (20) CONSTRAINT cust_first_name_not_null NOT NULL,
   cust_mid_name VARCHAR2 (20),
   cust_last_name VARCHAR2 (20) CONSTRAINT cust_last_name_not_null NOT NULL,
   account_type VARCHAR2 (15),
   cust_email VARCHAR2 (30),
   cust_mobile NUMBER (10),
   bank_id NUMBER (4),
   account_no NUMBER (4),
   CONSTRAINT cust_id_pri_key PRIMARY KEY (cust_id),
   CONSTRAINT cust_email_unq UNIQUE (cust_email),
   CONSTRAINT cust_mobile_unq UNIQUE (cust_mobile),
   CONSTRAINT bank_id_for_key FOREIGN KEY (bank_id) REFERENCES bank (bankid)
);

但是,我不会为命名NOT NULL约束而烦恼。命名它们并没有真正增加可管理性,因为它们可以通过在不知道名称的情况下更改表来更新。