Solved

SQL Script Help

Posted on 2013-12-10
12
264 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
U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

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…
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…
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

911 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

25 Experts available now in Live!

Get 1:1 Help Now