Question

I have two table in sql server:

First table Message_Child has a composite primary key (MessageId, ChildId)

Message_Child (MessageId, ChildId, Date)

Second table should contain a foreign key to Message_Child table, so I created two columns: MessageId and ChildId.

Request (RequestId, MessageId, ChildId, type)

And I created the constraint as follow:

Alter table Request
ADD FOREIGN KEY (MessageId, ChildId) REFERENCES Message_Child(MessageId, ChildId);

But I'm getting the following error:

There are no primary or candidate keys in the referenced table 'Message_Child' that match the referencing column list in the foreign key 'FK_Request_534D60F1'.

Edit Adding the code:

Message_Child table:

CREATE TABLE [dbo].[Message_Child](
[ChildId] [int] NOT NULL,
[MessageId] [int] NOT NULL,
[Date] [datetime] NULL,
 CONSTRAINT [PK_Message_Child] PRIMARY KEY CLUSTERED 
(
[ChildId] ASC,
[MessageId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,      ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Message_Child]  WITH CHECK ADD  CONSTRAINT          [FK_Message_Child_Child_ChildId] FOREIGN KEY([ChildId])
REFERENCES [dbo].[Child] ([ChildId])
GO

ALTER TABLE [dbo].[Message_Child] CHECK CONSTRAINT [FK_Message_Child_Child_ChildId]
GO

ALTER TABLE [dbo].[Message_Child]  WITH CHECK ADD  CONSTRAINT     [FK_Message_Child_Message_MessageId] FOREIGN KEY([MessageId])
REFERENCES [dbo].[Message] ([MessageId])
GO

ALTER TABLE [dbo].[Message_Child] CHECK CONSTRAINT [FK_Message_Child_Message_MessageId]
GO

RequestQueue table:

CREATE TABLE [dbo].[RequestQueue](
[RequestQueueId] [int] IDENTITY(1,1) NOT NULL,
[PIN] [nvarchar](max) NULL,
[MessageId] [int] NULL,
[ChildId] [int] NULL,
 CONSTRAINT [PK_RequestQueue] PRIMARY KEY CLUSTERED 
(
[RequestQueueId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,   ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[RequestQueue]  WITH CHECK ADD  CONSTRAINT   [FK_RequestQueue_MessageChildId] FOREIGN KEY([RequestQueueId])
REFERENCES [dbo].[RequestQueue] ([RequestQueueId])
GO

ALTER TABLE [dbo].[RequestQueue] CHECK CONSTRAINT [FK_RequestQueue_MessageChildId]
GO

And then I added this:

Alter table [DayCareDB].[dbo].[RequestQueue]
ADD FOREIGN KEY (MessageId, ChildId) REFERENCES [DayCareDB].[dbo].[Message_Child](MessageId, ChildId);
Was it helpful?

Solution

Key order matters here. You need to use (ChildID, MessageID) IN THAT ORDER since that is the key order in your primary key definition.

Alter table [DayCareDB].[dbo].[RequestQueue]
ADD FOREIGN KEY (ChildId, MessageId) 
REFERENCES [DayCareDB].[dbo].[Message_Child](ChildId, MessageId);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top