[英]SQL Server table creation error : There are no primary or candidate keys in the referenced
A very basic script is driving me crazy. 一个非常基本的脚本使我发疯。 It says it cant find a referenced key.
它说找不到引用的密钥。 Not idea what it's all about.
不知道这是怎么回事。 I'm am using SQL SERVER 2014 and this script is for the creation of my database tables.
我正在使用SQL SERVER 2014,此脚本用于创建数据库表。 I'm trying to make the
id_TABLE_1
in the table TABLE_2
reference the id of the table TABLE_1
. 我正在尝试使表
id_TABLE_1
中的TABLE_2
引用表TABLE_1
的ID。
CREATE TABLE TABLE_1
(
id int identity,
email varchar(50) not null,
constraint PK_TABLE_1 primary key (id,email)
)
GO
CREATE TABLE TABLE_2
(
id int identity,
id_TABLE_1 int not null,
constraint PK_TABLE_2 primary key (id),
constraint FK_TABLE_2 foreign key (id_TABLE_1)
references TABLE_1(id) on delete cascade
)
GO
The error is : 错误是:
Msg 1776, Level 16, State 0, Line 32
消息1776,级别16,状态0,第32行
There are no primary or candidate keys in the referenced table 'TABLE_1' that match the referencing column list in the foreign key 'FK_TABLE_2'.在引用表“ TABLE_1”中没有与外键“ FK_TABLE_2”中的引用列列表匹配的主键或候选键。
Msg 1750, Level 16, State 0, Line 32
消息1750,级别16,状态0,第32行
Could not create constraint or index.无法创建约束或索引。 See previous errors.
请参阅先前的错误。
Can you help me here ? 你能在这里帮我吗?
As per comment, you are trying to reference an index that doesn't exist. 根据评论,您正在尝试引用不存在的索引。 The primary key on your
TABLE_1
table is a composite key containing two columns: id
and email
. TABLE_1
表上的主键是一个复合键,其中包含两列: id
和email
。
For this to compile, you can either alter your primary key to: 为了进行编译,您可以将主键更改为:
CONSTRAINT PK_TABLE_1 PRIMARY KEY (id)
or create a new index on just the id
column: 或仅在
id
列上创建一个新索引:
CREATE INDEX IX_TABLE_1_id ON TABLE_1 (id);
It doesn't make sense to have a composite primary key that includes an identity column. 具有包含标识列的复合主键没有任何意义。 The id column is already unique and non-NULL, so it should be the primary key.
id列已经是唯一的并且不是NULL,因此它应该是主键。
If you want the email to be unique as well then remove it from the primary key and declare it as unique. 如果您还希望电子邮件具有唯一性,则将其从主键中删除并声明为唯一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.