Click here to Skip to main content
15,910,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I've 4 tables that suppose: t1.id is PK and t2.id,t3.id,t4.id are FK,now,
how can I delete a specific row(id) of all tables?
of course, I can do it with 4 DeleteCommands in a storedProcedure, but I think it's not optimized,is there better solution?
Posted

4 delete commands wrapped up in a transaction within a stored procedure is absolutely fine, you'd have to delete from the 'bottom up' though.

e.g

SQL
BEGIN TRANS

    DELETE FROM Table4 WHERE Table1_PK = 1

    DELETE FROM Table3 WHERE Table1_PK = 1

COMMIT TRANS


There's nothing wrong with that at all.

You could also enforce cascade deletes on your primary key (Table1) so that we you delete from this table, it automatically deletes all related data

It's up to you how to implement, personally I'm not massively keen on cascade deletes. I prefer to have to explicitly tell a database what to delete and get errors if something is accidentally deleted :)
 
Share this answer
 
Try the ff codes:

SQL
DELETE FROM t1
FROM t2
FROM t3
FROM t4
JOIN t2 ON t2.id = t1.id
JOIN t3 ON t3.id = t1.id
JOIN t4 ON t4.id = t1.id
WHERE id = @ID


I found this on the net. Here for your reference:
http://msdn.microsoft.com/en-us/library/ms189835.aspx[^]

Regards,
Eduard
 
Share this answer
 
You can apply cascaded delete to their relationship.

Open SSMS then go to design view of t1 then open Relationships window and set the Delete Rule of all relation to Cascade (in Insert and Update Specification section)

then save the changes.

From now on if you delete a record in t1 all the related rows in t2 , t3, t4 will be deleted automatically.

Hope it helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900