Why create a foreign key constraint that references the primary key of the same table from the primary key field
Asked Answered
G

1

6

I inherited a SQL Server database that has a table with a primary key named RecordID. The table definition and the foreign key defined like this:

CREATE TABLE [dbo].[MyTable](
  [RecordId] [int] IDENTITY(1,1) NOT NULL,
  [FileName] [nvarchar](255) NOT NULL,
  [Record] [nvarchar](255) NOT NULL,
  [ErrorDescription] [nvarchar](255) NULL,
  [ProcessDate] [datetime] NOT NULL,
 CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED 
(
  [RecordId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[MyTable]  WITH CHECK ADD  CONSTRAINT [FK_MyTable_MyTable] FOREIGN KEY([RecordId])
REFERENCES [dbo].[MyTable] ([RecordId])
GO

ALTER TABLE [dbo].[MyTable] CHECK CONSTRAINT [FK_MyTable_MyTable]
GO

I could understand this if the foreign key referenced from a different field in the same table back to the primaray key field which would allow for a heirarchy, but in this case the two fields in the foreign key definition are exactly the same field. Is this just a mistake in the original definition of the table and foreign key? Or is there a real advantage somehow to this?

Thanks in advance for your time in replying.

Getup answered 2/10, 2012 at 4:56 Comment(1)
Maybe check if there's another table in the database that looks like it should be referencing this table but isn't.Wield
T
4

Because the foreign key references itself, the check can never fail. That makes it, as a constraint, a no-op, so it is in every sense of the word, extraneous. Someone clearly made a mistake in creating the constraint.

I thought I might be missing something, so a quick check turned up with this: http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/342163/scope/posts.aspx which reinforces my suspicion (user error). My most educated conclusion is that someone at some stage thought of creating a self-referencing (other column) table constraint, but in a wicked twist of confusion created this abomination.

Toll answered 2/10, 2012 at 5:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.