Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

SQL Script Help

Posted on 2013-12-10
12
Medium Priority
?
274 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 27

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
Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

 
LVL 27

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 70

Accepted Solution

by:
Scott Pletcher earned 2000 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 70

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 27

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 70

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
This month, Experts Exchange sat down with resident SQL expert, Jim Horn, for an in-depth look into the makings of a successful career in SQL.
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…
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

618 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