Solved

delete a record that has a foreign key

Posted on 2014-12-15
1
73 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
1 Comment
 
LVL 65

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

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Join & Write a Comment

Performance is the key factor for any successful data integration project, knowing the type of transformation that you’re using is the first step on optimizing the SSIS flow performance, by utilizing the correct transformation or the design alternat…
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 …
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
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.

705 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now