• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 293
  • Last Modified:

deleting a record that has a foreign key

I have three tables in sql.  They are connected to each other via foreign keys.  If I want to delete the record associated in all 3 tables how do I do this.  When I simply deleting a record, I got this error:

Msg 547, Level 16, State 0, Line 1
The DELETE statement conflicted with the REFERENCE constraint "FK_tblOrgObjectives_tblOrgGoals". The conflict occurred in database "CAPRegistration", table "dbo.tblOrgObjectives", column 'GoalID'.
The statement has been terminated.
  • 2
2 Solutions
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
You can do this, but you'll have to do it IN ORDER from the child tables, working your way up to the parent table.

Spell out for us the relationship between these three tables.
al4629740Author Commented:
Dependence on each table is in this order
tblOrgGoals > tblOrgObjectives > tblPI

Primary > Foreign
tblOrgGoals > tblOrgObjectives : share the column GoalID

tblOrgObjectives > tblOrgPI : share the column ObjectiveID
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
>If I want to delete the record associated in all 3 tables
Just to get this show started, how 'about.....
Declare @GoalID int = 42

JOIN tblOrgObjectives ON  tblOrgPI.ObjectiveID  =  tblOrgObjectives.ObjectiveID 
WHERE tblOrgObjectives.GoalID = @GoalID

DELETE FROM tblOrgObjectives WHERE GoalID = @GoalID

DELETE FROM tblOrgGoals WHERE GoalID = @GoalID

Open in new window

What you really need is 'ON DELETE CASCADE' which will automatically track down all the foreign keys for a row being deleted and delete them too:


Rewrite your constraint scripts to include this clause and rebuild them. It will take a little time now but then in the future your deletes will be easy.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Build your data science skills into a career

Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now