Delete sql table parent child details

kasim mohamed 581 Reputation points
2021-03-06T09:21:11.83+00:00

Hi,

I have table like below.

create table #table (id int, description nvarchar(50), parentid int);

insert into #table values (1, 'Group1', 0)
insert into #table values (2, 'Group2', 0)

insert into #table values (11, 'Group1Sub1', 1)
insert into #table values (111, 'Group1Sub111', 11)
insert into #table values (112, 'Group1Sub112', 11)
insert into #table values (1111, 'Group1Sub1111', 111)
insert into #table values (1112, 'Group1Sub1112', 111)
insert into #table values (1121, 'Group1Sub1121', 112)

insert into #table values (21, 'Group2Sub1', 2)
insert into #table values (211, 'Group2Sub211', 21)
insert into #table values (212, 'Group2Sub212', 21)

select * from #table;
drop table #table;

I need to delete only the first group child items except first group first child.
Am looking the result like below table.

create table #resulttable (id int, description nvarchar(50), parentid int);

insert into #resulttable values (1, 'Group1', 0)
insert into #resulttable values (2, 'Group2', 0)

insert into #resulttable values (11, 'Group1Sub1', 1)

insert into #resulttable values (21, 'Group2Sub1', 2)
insert into #resulttable values (211, 'Group2Sub211', 21)
insert into #resulttable values (212, 'Group2Sub212', 21)

select * from #resulttable;
drop table #resulttable;

Thanks in Advance

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,815 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,559 questions
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 101.9K Reputation points MVP
    2021-03-06T11:27:09.44+00:00

    You will need to find out how you define what is the "first group". Here I've just hard-coded it in a variable.

    DECLARE @firstgroup nvarchar(50) = 'Group1'
    
    ; WITH recurs AS (
       SELECT id, lvl = 1
       FROM   #table
       WHERE  description = @firstgroup
       UNION ALL
       SELECT t.id, r.lvl + 1
       FROM   recurs r
       JOIN   #table t ON t.parentid = r.id
    )
    DELETE #table 
    FROM   #table t
    WHERE  EXISTS (SELECT *
                   FROM   recurs r
                   WHERE  r.id = t.id
                     AND  r.lvl > 2)
    

0 additional answers

Sort by: Most helpful