Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 delete parent and all children

Author  Topic 

sarahmfr
Posting Yak Master

214 Posts

Posted - 2012-01-31 : 15:29:00
I have a table sectionlesson (lessonid,sectionid)
and another lesson(lessonid, description,title etc)
I want to delete the record in sectionlesson for sectionid=x and all related lessons
Thanks

sarah

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-01-31 : 18:58:04
You can do two deletes; You may want to wrap it in a transaction and try-catch block to preserve data integrity. The other option is to use CASCADE DELETE if you have the proper foreign keys.
DECLARE @x INT;
SET @x=123;

DELETE FROM lesson WHERE lessonid IN
(SELECT lessonid FROM sectionlesson WHERE sectionid = @x);
DELETE FROM sectionlesson WHERE sectionid = @x;
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-01-31 : 19:03:52
see

http://visakhm.blogspot.com/2011/11/recursive-delete-from-parent-child.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -