[英]SQL Server : there are no primary or candidate keys in the referenced table
I using SQL Server 2008, and when I try create a new table, in existing DB, this error appears: 我使用SQL Server 2008,当我尝试在现有数据库中创建新表时,出现此错误:
There are no primary or candidate keys in the referenced table 'parceria_conta_corrente_ao' that match the referencing column list in the foreign key 'R_795'.
在引用表“ parceria_conta_corrente_ao”中没有与外键“ R_795”中的引用列列表匹配的主键或候选键。
This table exists: 该表存在:
And I try create a new table with this code: 我尝试使用以下代码创建一个新表:
CREATE TABLE parceria_item_resgate_rateio_aux
(
id_parceria_item_resgate_rateio_aux int NOT NULL IDENTITY,
dt_conta_corrente DATETIME NOT NULL ,
id_periodo BIGINT NOT NULL ,
id_ao bigint NOT NULL ,
id_gr_cliente int NOT NULL ,
id_cliente BIGINT NOT NULL ,
data_importacao_cli_gr_cli DATETIME NOT NULL ,
hp2 varchar(50) NOT NULL ,
hp2_filho varchar(50) NOT NULL ,
valor_nc decimal(18,2) NULL ,
datetime_inclusion datetime NOT NULL ,
status int NULL ,
CONSTRAINT XPKparceria_item_resgate_ PRIMARY KEY CLUSTERED
(id_parceria_item_resgate_rateio_aux ASC,
dt_conta_corrente ASC,
id_periodo ASC,
id_ao ASC,
id_gr_cliente ASC,
id_cliente ASC,
data_importacao_cli_gr_cli ASC,
hp2 ASC),
CONSTRAINT R_795 FOREIGN KEY(dt_conta_corrente, id_periodo, id_ao, id_gr_cliente, id_cliente, data_importacao_cli_gr_cli, hp2)
REFERENCES parceria_conta_corrente_ao(dt_conta_corrente, id_periodo, id_ao, id_gr_cliente, id_cliente, data_importacao_cli_gr_cli, hp2)
ON DELETE CASCADE
ON UPDATE CASCADE
)
go
Where is the problem? 问题出在哪儿?
You need to create a unique index on the referenced table: 您需要在引用表上创建唯一索引:
CREATE UNIQUE INDEX UX_parceria_conta_corrente_ao
ON parceria_conta_corrente_ao
(
dt_conta_corrente,
id_periodo,
id_ao,
id_gr_cliente,
id_cliente,
data_importacao_cli_gr_cli,
hp2
)
EDIT: I guess the columns are not in the same order, columns in primary key must be in the same order than the columns in the foreing key. 编辑:我想列不按相同的顺序,主键中的列必须比前键中的列以相同的顺序。
If you execute the following: 如果执行以下操作:
CREATE TABLE T
(
C1 int NOT NULL,
C2 int NOT NULL,
PRIMARY KEY (C1, C2)
)
CREATE TABLE T2
(
id INT NOT NULL,
C1 int NOT NULL,
C2 int NOT NULL,
CONSTRAINT FK1 FOREIGN KEY (C2, C1) REFERENCES T(C2, C1)
)
You get the following error: 您收到以下错误:
Msg 1776, Level 16, State 0, Line 9 There are no primary or candidate keys in the referenced table 'T' that match the referencing column list in the foreign key 'FK1'.
消息1776,级别16,状态0,第9行,在被引用表'T'中没有与外键'FK1'中的引用列列表匹配的主键或候选键。 Msg 1750, Level 16, State 0, Line 9 Could not create constraint or index.
消息1750,级别16,状态0,第9行无法创建约束或索引。 See previous errors.
请参阅先前的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.