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 2005 Forums
 Transact-SQL (2005)
 CASCADE DELETE N SAME TABLE

Author  Topic 

sateesh.sqldba
Starting Member

25 Posts

Posted - 2010-09-21 : 00:15:20
Hi Experts,

i am having table like


ID NAME PAREND_ID

1 F1 0

2 F2 1
3 F3 1
4 F4 2
5 F5 3

like this i have if i delete parent_ID 1 then i want to delete ID(2,3) because those will become orphans ....

Thank you Inadvance....

sateesh

PavanKK
Starting Member

32 Posts

Posted - 2010-09-21 : 01:36:06
Hi Sateesh,

This will delete recursive childs for given ParentID.

-----------

DECLARE @T TABLE(ID INT,NAME VARCHAR(10),PAREND_ID INT)

INSERT @T VALUES (1,'F1',0)
INSERT @T VALUES (2,'F2',1)
INSERT @T VALUES (3,'F3',1)
INSERT @T VALUES (4,'F4',2)
INSERT @T VALUES (5,'F5',3)
INSERT @T VALUES (6,'F6',0)
INSERT @T VALUES (7,'F7',6)

;WITH Cte AS
(
SELECT 1 AS ID

UNION ALL

SELECT T.ID
FROM @T T
JOIN Cte C ON T.PAREND_ID = C.ID
)

DELETE T
FROM @T T
JOIN Cte C ON T.ID = C.ID

---------



KK
Go to Top of Page
   

- Advertisement -