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


I am facing an issue while deleting row from multiple table in a single query.
My tables are : Event - Parent Table which have EventID as an primary key in it.
The other tables which contains the EventID as foreign key are :

Coordinator
Event_Attendee_Organizer
Event_Organizer
Invitation
Slot

I want to delete the particular rows from all the tables where eventid and organizerid matches. The OrganizerID is present in Event_Attendee_Organizer and Event_Organizer table.

Please help me to solve this issue.

Thanks in advance...
Posted

Try this:
SQL
DELETE t1,t2,t3 FROM table1 as t1
JOIN table2 as t2 ON t2.ID = t1.ID
JOIN table3 as t3 ON t3.ID = t1.ID


Your eventID in all table will make it work.

For deleting records from multiple tables:
You could define Foreign Key constraints (which you have defined as EventID) for the other tables that reference the master table's ID with ON DELETE CASCADE.
This would cause the related rows in those tables to be deleted. This is the least programming model, is part of the SQL standard, etc. Just be sure that you think through the issues with always deleting the referencing rows.
Refer for more details: http://msdn.microsoft.com/en-us/library/ms174979.aspx[^]

You could create a delete trigger on the table where you delete the master row for the ID that would then contain code to delete related rows
from other tables.
You still have to write the code for this one, but it hides inside the trigger and is used by any deletes from the table as long as the trigger is not disabled.
Refer for more details: http://msdn.microsoft.com/en-us/library/ms189799.aspx[^]
 
Share this answer
 
Comments
Manas Bhardwaj 21-Aug-12 9:14am    
+5
Prasad_Kulkarni 22-Aug-12 0:03am    
Thank you Manas!
Try this

 BEGIN TRY
   BEGIN TRANSACTION

   DELETE EAO
   FROM Event_Attendee_Organizer EAO
   INNER JOIN [Event] E ON EAO.OrganizerID = E.EventID


   DELETE EO
   FROM Event_Organizer  EO
   INNER JOIN [Event] E ON EO.OrganizerID = E.EventID

   COMMIT TRANSACTION
END TRY
BEGIN CATCH
   ROLLBACK TRANSACTION
END CATCH
 
Share this answer
 
Just do a cascade delete for this one.
 
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