Solved

delete a record that has a foreign key

Posted on 2014-12-15
1
80 Views
Last Modified: 2014-12-16
I have the following SQL JOIN statement

select * from tblOrgGoals G
Inner Join tblOrgObjectives O on G.GoalID = O.GoalID
Inner Join tblOrgPI P on O.ObjectiveID = P.ObjectiveID

If I would like to delete a record from tblOrgGoals and it is linked to the other two tables, how would I be able to cascade delete all the records that record has a relationship with?

Can I also delete a record from tblOrgPI and cascade delete in the other direction?
0
Comment
Question by:al4629740
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 66

Accepted Solution

by:
Jim Horn earned 500 total points
ID: 40501038
Assuming you know the GoalID (42 here), you could delete the row(s) from the related table, then the goal table.  
All in a transaction so the set of deletes succeed or fail together.
BEGIN TRY
  BEGIN TRAN tr

  DELETE P
  FROM tblOrgPI P
     Join tblOrgObjectives O ON O.ObjectiveID = P.ObjectiveID
  WHERE O.GoalID = 42

  DELETE O
  FROM tblOrgObjectives O
  WHERE O.GoalID = 42

  DELETE FROM tblOrgGoals WHERE GoalID=42 

  -- If code execution makes it here, good to go
  COMMIT TRAN tr
END TRY

BEGIN CATCH
  -- Ruh roh.  An error occured. 
  PRINT 'An error occured'
  ROLLBACK TRAN tr
END CATCH

Open in new window

0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question