2011-12-12 95 views
0

我试图执行我通过Microsoft Visio的Forward Engineer Addin创建的数据库脚本。SQL Server否匹配键错误消息

以下是我收到错误和错误信息被引用的代码的部分:

错误1:

Msg 1776, Level 16, State 0, Line 12 
There are no primary or candidate keys in the referenced table 'dbo.Account_BillingAccount' that match the referencing column list in the foreign key 'Account_BillingAccount_InvoiceDetail_FK1'. 
Msg 1750, Level 16, State 0, Line 12 
Could not create constraint. See previous errors. 

代码文献1:

ALTER TABLE [dbo].[InvoiceDetail] WITH CHECK ADD CONSTRAINT [Account_BillingAccount_InvoiceDetail_FK1] FOREIGN KEY (
[BillingAccountNumber] 
, [AccountNumber] 
) 
REFERENCES [dbo].[Account_BillingAccount] (
[BillingAccountNumber] 
, [AccountNumber] 
) 

错误2:

Msg 1776, Level 16, State 0, Line 2 
There are no primary or candidate keys in the referenced table 'dbo.ManagerContract' that match the referencing column list in the foreign key 'ManagerContract_RegionalCoordinators_FK1'. 
Msg 1750, Level 16, State 0, Line 2 
Could not create constraint. See previous errors. 

代码参考2:

ALTER TABLE [dbo].[RegionalCoordinators] WITH CHECK ADD CONSTRAINT [ManagerContract_RegionalCoordinators_FK1] FOREIGN KEY (
[AssociateID] 
, [WritingNumber] 
) 
REFERENCES [dbo].[ManagerContract] (
[AssociateID] 
, [WritingNumber] 
) 

什么是消除上述误差的最有效方法是什么?

+1

您必须在引用表中具有与列列表匹配的主键或唯一键。因此,在'ManagerContract'中,您需要'AssociateID,WritingNumber'和'Account_BillingAccount'上的唯一键,您需要'BillingAccountNumber,AccountNumber'。 –

+0

添加此唯一密钥的语法是什么? – idealistikz

回答

0

您必须在引用表中与列列表匹配的主键或唯一键。因此,在ManagerContract中,您需要AssociateID, WritingNumberAccount_BillingAccount上的唯一密钥,您需要它BillingAccountNumber, AccountNumber

查看有关如何创建唯一约束的信息。 http://msdn.microsoft.com/en-us/library/ms191166.aspx

ALTER TABLE [DBO]。[表名]添加约束 UNQ_ 表名 _ColumnName UNIQUE([的ColumnName])

像这样的事情在你的情况。

alter table dbo.ManagerContract 
add constraint UNQ_ManagerContract_AssociateID_WritingNumber 
unique (AssociateID, WritingNumber) 
+0

我已经有AssociateID和WritingNumber作为ManagerContract的主键。我是否仍然需要将它们包含为唯一键? – idealistikz

+0

@idealistikz - 不,那应该够了。当你的SQL脚本尝试添加FK时,你确定它们在那里吗?也许你的脚本中存在一个依赖性和执行语句顺序的问题? –

+0

在ALTER TABLE语句之前,将AssociateID和WritingNumber设置为主键。可能是什么问题? – idealistikz