如何在Oracle 10g中分配外键?

时间:2015-02-03 08:40:41

标签: oracle

我尝试在Oracle 10g中分配外键。但错误显示为

ORA-907:错过右括号

我有三张桌子

TblCustomer
TblProducts
TblSales

create table tblSales
(SalesID int primary key,
ProductId int foreign key references tblProducts(ProductId),
CustomerID int foreign key references tblCustomer(CustomerID),
SalesPrice numeric,
SalesDate date);

你可能会建议我出错。

2 个答案:

答案 0 :(得分:2)

您的语法必须如下:

create table tblSales (SalesID int, 
ProductId int , 
CustomerID int , 
SalesPrice numeric, 
SalesDate date,
CONSTRAINT sales_pk PRIMARY KEY (SalesID ),
CONSTRAINT fk_produkt
foreign key (ProductId)references tblProducts(ProductId),
CONSTRAINT fk_customer
foreign key (CustomerID)references tblCustomer(CustomerID)

);

答案 1 :(得分:2)

对于内联外键,您不指定foreign key关键字:

create table tblSales
(
   SalesID int primary key,
   ProductId int references tblProducts(ProductId),
   CustomerID int references tblCustomer(CustomerID),
   SalesPrice numeric,
   SalesDate date
);

使用内联外键,您甚至不需要指定目标列:

create table tblSales
(
   SalesID int primary key,
   ProductId int references tblProducts,
   CustomerID int references tblCustomer,
   SalesPrice numeric,
   SalesDate date
);

SQLFiddle示例:http://sqlfiddle.com/#!4/420b9c


作为旁注:给每个表添加tbl前缀并没有多大意义。如果您正在编程,是否为每个班级添加Cls作为前缀,或者如果您为某人命名,是否为每个姓名添加Pers前缀?功能