Skip to content
Advertisement

Can Foreign Key on a table be three different tables as primary keys (each table primary key data is different)?

I have a reminder table (ParentId) – Foreign key to ProductId from Product and also OrderId from Order table. Is it possible? When I try to insert the data for the Reminder table belongs to OrderId, I’m getting Foreign-Key constraint error.

Reminder
 - ReminderId
 - ParentId

Product
 - ProductId

Order
 - OrderId

ALTER TABLE [dbo].[Reminder]  WITH NOCHECK ADD  CONSTRAINT [FK_Reminder_ProductId] FOREIGN KEY([ParentId])

REFERENCES [dbo].[Product] ([ProductId])
GO

ALTER TABLE [dbo].[Reminder] NOCHECK CONSTRAINT [FK_Reminder_ProductId]
GO

ALTER TABLE [dbo].[Reminder]  WITH NOCHECK ADD  CONSTRAINT [FK_Reminder_OrderId] FOREIGN KEY([ParentId])
REFERENCES [dbo].[Quote] ([QuoteId])
GO

ALTER TABLE [dbo].[Reminder] NOCHECK CONSTRAINT [FK_Reminder_OrderId]
GO

Advertisement

Answer

You can do this with a bit of work, using foreign key relationships and computed columns. This does require a “type” of some sort in the table:

create table reminders (
    ReminderId . . . primary key,
    parentId int, -- presumably
    type varchar(255),
    check (type in ('product', 'order')),
    parent_productid as (case when type = 'product' then parentId end) persisted,
    parent_orderid as (case when type = 'order' then parentId end) persisted,
    foreign key (parent_productid) references products(productId),
    foreign key (parent_orderid) references orders(orderid)
);

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement