日期:2014-05-18  浏览次数:20726 次

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

------解决方案--------------------
http://blog.csdn.net/softkexin/article/details/7389443
------解决方案--------------------
你可以考虑写一个存储过程,将父级ID传入进去.

执行删除操作.
------解决方案--------------------
以下是大概思路, 没经过测试,你看着加一下注释部分的方法应该就可以了。


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
}
}



------解决方案--------------------
SQL code

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',0

create 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