Solved

delete a record that has a foreign key

Posted on 2014-12-15
1
76 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

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

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

When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Viewers will learn how the fundamental information of how to create a table.

774 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