我正在尝试创建复合外键关系/约束。所有表都是空的。我有这张桌子:
CREATE TABLE [dbo].[ChemSampleValueTest](
[SampleNumber] [int] NOT NULL,
[ParameterID] [int] NOT NULL,
[Value] [numeric](18, 6) NOT NULL,
[Accuracy] [varchar](50) NULL,
[ResultGroupID] [int] NOT NULL,
[QAState] [nvarchar](32) NOT NULL,
CONSTRAINT [PK_SampleValueTest] PRIMARY KEY CLUSTERED
(
[SampleNumber] ASC,
[ParameterID] ASC,
[ResultGroupID] ASC
)
) ON [PRIMARY]
和这张表:
CREATE TABLE [dbo].[ChemSampleValueEventLinkTest](
[Event] [int] NOT NULL,
[SampleNumber] [int] NOT NULL,
[ResultGroupID] [int] NOT NULL,
[ParameterID] [int] NOT NULL,
[QAState] [nvarchar](32) NULL
) ON [PRIMARY]
我希望将它们链接起来:
alter table [ChemSampleValueEventLinkTest] add
constraint FK_ChemSampleValueEvent_ChemSampleValue_test
foreign key ([SampleNumber], [ResultGroupID], [ParameterID])
references ChemSampleValueTest ([SampleNumber], [ResultGroupID], [ParameterID])
据我所知,所有列类型都相同,但它一直在说
引用的表中没有主键或候选键 'ChemSampleValueTest'与外键中的引用列列表匹配 'FK_ChemSampleValueEvent_ChemSampleValue_test'。
我哪里错了?
答案 0 :(得分:15)
看起来您需要按照它们在PK定义中出现的顺序来显示您的FK /引用列表。
这应该有效:
CREATE TABLE [dbo].[ChemSampleValueTest](
[SampleNumber] [int] NOT NULL,
[ParameterID] [int] NOT NULL,
[Value] [numeric](18, 6) NOT NULL,
[Accuracy] [varchar](50) NULL,
[ResultGroupID] [int] NOT NULL,
[QAState] [nvarchar](32) NOT NULL,
CONSTRAINT [PK_SampleValueTest] PRIMARY KEY CLUSTERED
(
[SampleNumber] ASC,
[ParameterID] ASC,
[ResultGroupID] ASC
)
) ON [PRIMARY]
CREATE TABLE [dbo].[ChemSampleValueEventLinkTest](
[Event] [int] NOT NULL,
[SampleNumber] [int] NOT NULL,
[ResultGroupID] [int] NOT NULL,
[ParameterID] [int] NOT NULL,
[QAState] [nvarchar](32) NULL
) ON [PRIMARY]
alter table [ChemSampleValueEventLinkTest] add
constraint FK_ChemSampleValueEvent_ChemSampleValue_test
foreign key ([SampleNumber], [ParameterID], [ResultGroupID])
references ChemSampleValueTest ([SampleNumber], [ParameterID], [ResultGroupID])