求写一个递归方法
求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
}
}
[解决办法]
use DBTestgoif OBJECT_ID('tabTest') is not null drop table tabTestgocreate table tabTest(ID int,Name nvarchar(20),PID int)goinsert into tabTestselect 1,'a',0 union allselect 2,'b',1 union allselect 3,'c',0create proc procTest(@ID int)ASwith CTETestas(select * from tabTest where ID=@IDunion all(select a.* from tabTest as a inner joinCTETest as b on a.PID=b.ID))delete from tabTest where ID in(select ID from CTETest)GO