Solved

SQL Script Help

Posted on 2013-12-10
12
267 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

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

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

749 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