Solved

hierarchy delete

Posted on 2013-11-29
1
139 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

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

910 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now