删除父子结构表中数据SQL语句

来源:互联网 发布:脑白金 网络推广 编辑:程序博客网 时间:2024/05/22 03:49

例如表department中有字段deptid,parentid。当删除一个父结点时,删除它的其下的所有子结点。
注:此方法只能在SQL Server 2005中使用,SQL Server 2000不支持。
WITH tempdept AS
     ( SELECT root.deptid, root.parentid
            FROM department root
            WHERE deptid=1
      UNION all
       SELECT sub.deptid, sub.parentid
            FROM department sub, tempdept super
            WHERE sub.parentid = super.deptid
      )
delete from department where deptid in
       (  select deptid from tempdept  )
删除后查看是否正确。已测试。
select * from department