?
Solved

hierarchy delete

Posted on 2013-11-29
1
Medium Priority
?
159 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 50

Accepted Solution

by:
Lowfatspread earned 2000 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

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

741 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