Solved

hierarchy delete

Posted on 2013-11-29
1
144 Views
Last Modified: 2013-12-13
Hello,
How can I delete hierarchy from the root down? ParentId refers to Id from another row.
In the example below I would want to delete first 3 rows by passing in Id=1

DECLARE @Table table(Id int, ParentId int, MyText varchar(50))

INSERT INTO @Table(Id, ParentId, MyText) values(1,0,'One')
INSERT INTO @Table(Id, ParentId, MyText) values(2,1,'1.1')
INSERT INTO @Table(Id, ParentId, MyText) values(3,2,'1.1.1')
INSERT INTO @Table(Id, ParentId, MyText) values(4,0,'Two')
0
Comment
Question by:johnson1
1 Comment
 
LVL 50

Accepted Solution

by:
Lowfatspread earned 500 total points
ID: 39685441
use a recursive cte

;with cte as (
  select a.*
    from @table
    where id=1
  union all
  select a.*
    from @table as a
   Inner join cte as b
      on a.id=b.parentid
  )
 Delete x
   from @table as X
   Inner join CTE
     on x.id=cte.id
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone 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

Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

685 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