Solved

SQL Script Help

Posted on 2013-12-10
12
260 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
 
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
Zoho SalesIQ

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

 
LVL 69

Accepted Solution

by:
ScottPletcher 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:ScottPletcher
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:ScottPletcher
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

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…
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…
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 setup several different housekeeping processes for a SQL Server.

744 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

12 Experts available now in Live!

Get 1:1 Help Now