Solved

delete a record that has a foreign key

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

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to shrink a transaction log file down to a reasonable size.

828 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