从SQL Server层次结构中删除重复节点

时间:2016-06-17 08:47:53

标签: sql sql-server sql-server-2008 hierarchy

查看以下数据可以轻松找到同一叶子下更高级别的ID并将其删除。

E.g。 ID 4,5存在于行4,5,8,9和12,13中。 我想删除第4,5行,因为层次结构中存在相同的ID(第8,9行),但第12,13行保留在单独的叶子上。

Rows to be Removed

await

2 个答案:

答案 0 :(得分:0)

最大ID len = 1

的示例
select *
--delete t1
    from table as t1
    where exists(
            select *
                from table as t2
                where left(t2.path, len(t1.path - 2)) = left(t1.path, len(t1.path - 2))
                    and charindex(right(t1.path, 2), t2.path, len(t1.path)) > 0
        ) 

答案 1 :(得分:0)

这是我的方法,它适用于任何长度的ID:

with 
conversed as (
select substring(reverse(path),CHARINDEX('/',reverse(path),2), len(path)-CHARINDEX('/',reverse(path),2)) inverse_path, id, t.row
  from t)
select c.id, c.row keeper, c1.row deletethis  
  from conversed c join conversed c1 
    on c.id = c1.id 
   and c.row <> c1.row
   and c.inverse_path like '%' +c1.inverse_path;

<强>输出

id  keeper  deletethis
4   8       4
5   9       5