Why create a foreign key constraint that refers to the primary key of the same table from the primary key field

I inherited a SQL Server database that has a table with a primary key called RecordID. The table definition and foreign key are defined as follows:

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 is referenced from another field in the same table back to the primaray key field field, which would allow the hierarchy to be used, but in this case the two fields in the foreign key definition are exactly the same field, This is just a mistake initial definition of table and foreign key? Or is there any real advantage to this?

Thanks in advance for your time in reply.

+6
source share
1 answer

Because the foreign key refers to itself, validation can never fail. This makes it, as a restriction, non-op, so it is in every sense of the word, an outsider. Someone clearly made a mistake when creating the constraint.

I thought that maybe something is missing, so a check quickly appeared 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 about creating a table binding with a binding (another column), but in an evil turn of confusion created this abomination.

+4
source

Source: https://habr.com/ru/post/926724/


All Articles