Solved

SQL Script Help

Posted on 2013-12-10
12
265 Views
Last Modified: 2013-12-11
I need help writing a script that removes rows from a child table first and then removes rows from a primary table.  

Constraint name = FK_tbAccidentParticipant_tbAccident if that even matters.

Foreign key table. Can contain 1 or many rows. (Foreign key = AccidentId)
select *   FROM tbAccidentParticipant where AccidentId = 2744

Primary key table.  Always 1 row.  (Primary Key = Id)
SELECT *   FROM [tbAccident]  where Id = 2744

What I need to be able to execute is some sort of script that removes the foreign key row(s) first and then removes the 1 row from the primary table.

Transaction is optional but preferred.  This would be executed in sql server mgmt studio 2012.
0
Comment
Question by:hougie40
  • 4
  • 3
  • 3
  • +2
12 Comments
 
LVL 26

Expert Comment

by:Zberteoc
ID: 39710001
Why don't you enable the cascade delete option for the FK and then you can directly delete the parent row?
0
 
LVL 34

Expert Comment

by:Brian Crowe
ID: 39710016
what parameters are you providing to determine which rows to delete?
0
 
LVL 9

Expert Comment

by:COANetwork
ID: 39710021
BEGIN TRAN
DECLARE @intErr int
DELETE FROM tbAccidentParticipant WHERE AccidentId = 2744;
SELECT @intErr = @@ERROR;
DELETE FROM [tbAccident]  WHERE Id = 2744;
IF (@@ERROR = 0 AND @intErr = 0)
    COMMIT TRAN
ELSE
    ROLLBACK TRAN
END TRAN

That's given your hardcoded values, of course.  Plug in parameters where needed.
0
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.

 
LVL 26

Expert Comment

by:Zberteoc
ID: 39710044
To change to cascade delete you need to go in design mode in the child table, tbAccidentParticipant, click on Relationship menu icon, select the FK, at the bottom in the right panel expand INSERT and UPDATE Specific node and beneath, next to the Delete Rule you choose from the dropdown the Cascade option. Close and then save.

As a result when you will delete a row from the parent table all its associated rows from the child table will be deleted as well.
0
 

Author Comment

by:hougie40
ID: 39710084
COANetwork.  I like it.  Trouble is I get a syntax error I wanted to show you.  Is there any adjusting necessary?

It doesnt like the End Tran
0
 

Author Comment

by:hougie40
ID: 39710085
Zberteoc,

Im guessing my dba doesnt allow that technique.  He is pretty picky.  He prefers scripting everything :(
0
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 500 total points
ID: 39710093
DECLARE @AccidentId int
SET @AccidentId = 2744

BEGIN TRY
BEGIN TRANSACTION
DELETE FROM dbo.tbAccidentParticipant WHERE AccidentId = @AccidentId
DELETE FROM dbo.tbAccident WHERE Id = @AccidentId
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0
    ROLLBACK TRANSACTION
 SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage
END CATCH
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 39710096
>> Im guessing my dba doesnt allow that technique.  He prefers scripting everything :( <<

100% right!  I script everything rather than risk inconsistent and/or undesired results.
0
 
LVL 26

Expert Comment

by:Zberteoc
ID: 39710395
A relation with cascade delete it is safer then any script, not to mention simpler and with no maintenance needed.

Houghie, that error happens because of that END TRAN line, which is not part of the syntax. Just remove and should work. An explicit transaction ends with either commit or rollback or with both but in an IF branch.
0
 

Author Comment

by:hougie40
ID: 39711414
I see both sides of the argument ie scripting way or not scripting.   I tend to be a guy who trusts the tools more though.  Maybe im lazy.  BUT im not the dba :)  

I really appreciate all you guys help and scott pletcher i like the script you added too.  Today is my birthday so this has been a nice present!
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 39711433
CASCADE can give you some nasty surprises later by deleting far more rows than you imagined it would after you've linked several more tables with foreign keys.

Any hand-coded delete script does need to be dynamic, though.  It should not have only hard-coded, existing relationships, but should be able to dynamically check for other parent-child relationships.
0
 

Author Closing Comment

by:hougie40
ID: 39711539
Thanks Scott.
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

813 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

14 Experts available now in Live!

Get 1:1 Help Now