求C#中写一个递归删除的方法,这张表的字段是ID,NAME,PID, PID存的是上级的ID。这个方法参数只有ID和实体Entity。
实体是数据库中映射出来的!

解决方案 »

  1.   

    Sqlserver2005及更高版本支持递归。数据库版块有现成的,你查一下。
      

  2.   

    http://blog.csdn.net/softkexin/article/details/7389443
      

  3.   

    以下是大概思路, 没经过测试,你看着加一下注释部分的方法应该就可以了。
    void delEntityAndChild(int id){
      int pid=0;
     // 这里查一下 pid = id 的列表, 
     //   select id from "tablename" where pid=@id  foreach(datarow dr in dt.rows)
     {
        // 这里递归了, 查得到的 ID 有没有 pid 等于它的
        int tmppid = Convert.ToInt32(dr["id"]);
        // 大于 0 是考虑,可能一级节点的 pid =0
        if(tmppid >0){
         delEntityAndChild(pid);
        }
        // 执行删除
        //    delete from "tablename" where id = @id
      }
    }
      

  4.   


    use DBTest
    go
    if OBJECT_ID('tabTest') is not null drop table tabTest
    go
    create table tabTest
    (
    ID int,
    Name nvarchar(20),
    PID int
    )
    go
    insert into tabTest
    select 1,'a',0 union all
    select 2,'b',1 union all
    select 3,'c',0create proc procTest(@ID int)
    AS
    with CTETest
    as
    (
    select * from tabTest where ID=@ID
    union all
    (
    select a.* from tabTest as a inner join
    CTETest as b on a.PID=b.ID
    )
    )
    delete from tabTest where ID in(select ID  from CTETest)
    GO