. Advertisement .
..3..
. Advertisement .
..4..
I get the error: the insert statement conflicted with the foreign key constraint when I try to run the program below:
CREATE TABLE [dbo].[Person](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PersonDetails](
[ID] [int] IDENTITY(1,1) NOT NULL,
[PersonID] int NOT NULL,
[SurName] [varchar](50) NULL,
[Age] int
) ON [PRIMARY]
GO
Now let’s set the PersonID column in the PersonDetails table as the Foreign Key of the Primary Key in the Person table.
|
|
USE [TestDB]
GO
INSERT INTO [dbo].[PersonDetails] ([PersonID],[SurName],[Age]) VALUES (1,'CAKIR',34)
GO
The error appears the system notifies as follows:
Msg 547, Level 16, State 0, Line 3
The INSERT statement conflicted with the FOREIGN KEY constraint “FK_PersonDetails_Person”.
The conflict occurred in database “TestDB”, table “dbo.Person”, column ‘ID’.
The statement has been terminated.
I tried to solve it with another sample. I got the reference in the community forum, but it still returned an invalid result. If someone knows the solution, please give me the support. Thanks!
The cause: The Primary table does not have the corresponding ID value.
Solution: Add a record to the primary table first.
This error message was sent to me when I tried to populate foreign key fields. This page was the first place I looked to find the solution. Although the page has the correct answer, I believe the information is not complete for those who aren’t as familiar with SQL. Although I’m fairly proficient at writing code, SQL queries and building tables are still new to me.
The checked answer is correct, but:
This answer does not include the following:
Another way is to say it:
This is because many tutorials gloss over the fact that you will get an error if you try to do it yourself and don’t know how to order operations. This error will continue even if you have added the primary key data. Otherwise, the foreign key data in your child table must match the primary key field of the parent table.
This is the final version. This should have made the check answer clearer. Some people may think that this is a straightforward task and that reading a book would have solved the question. But, the truth is that everyone learns differently.