C# 基于SQL Server的父id行递归更新值
我有下面的表结构C# 基于SQL Server的父id行递归更新值,c#,asp.net,sql-server,sql-server-2008,recursion,C#,Asp.net,Sql Server,Sql Server 2008,Recursion,我有下面的表结构 | id | parentID | count1 | 2 -1 1 3 2 1 4 2 0 5 3 1 6 5 0 我从源代码中增加了计数值,但我还需要增加的数值冒泡到每个父id行,直到父id为-1 如果我将第6行上的count1增加1,第5行将增加1,第3行将增加1,第2行将增加1 行也会被删除,相反的情况需要发生,
| id | parentID | count1 |
2 -1 1
3 2 1
4 2 0
5 3 1
6 5 0
我从源代码中增加了计数值,但我还需要增加的数值冒泡到每个父id行,直到父id为-1
如果我将第6行上的count1增加1,第5行将增加1,第3行将增加1,第2行将增加1
行也会被删除,相反的情况需要发生,基本上是从每个父行中减去要删除的行的值
提前感谢您的洞察力
我使用的是SQL Server 2008和C asp.net。您希望为此使用递归CTE:
with cte as (
select id, id as parentid, 1 as level
from t
union all
select cte.id, t.parentid, cte.level + 1
from t join
cte
on t.id = cte.parentid
where cte.parentid <> -1
) --select parentid from cte where id = 6
update t
set count1 = count1 + 1
where id in (select parentid from cte where id = 6);
以下是。如果您真的只想更新计数,您可以编写存储过程来执行此操作:
create procedure usp_temp_update
(
@id int,
@value int = 1
)
as
begin
with cte as (
-- Take record
select t.id, t.parentid from temp as t where t.id = @id
union all
-- And all parents recursively
select t.id, t.parentid
from cte as c
inner join temp as t on t.id = c.parentid
)
update temp set
cnt = cnt + @value
where id in (select id from cte)
end
因此,您可以在插入和删除行后调用它。但是,如果您的计数字段仅取决于您的表,我建议您创建一个触发器,该触发器将重新计算您的值您是否使用Linq to SQL?我不是,仅使用SQLCommands我建议使用CTE来处理此问题。