Solved

hierarchy delete

Posted on 2013-11-29
1
138 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
Comment Utility
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

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 …
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

763 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

13 Experts available now in Live!

Get 1:1 Help Now