![](/img/trans.png)
[英]rows in sql server db being deleted once I click update. the id is only filed that has data
[英]Recursively update values based on rows parent id SQL Server
我有以下表格结构
| id | parentID | count1 |
2 -1 1
3 2 1
4 2 0
5 3 1
6 5 0
我从源代码中增加计数值,但我还需要增加值以使每个父ID行冒泡直到父ID为-1。
例如。 如果我要将行ID#6的count1
增加1,则行ID#5将增加1,ID#3将增加1,ID#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);
这是SQL Fiddle 。
如果您确实只想更新计数,则可以编写存储过程来做到这一点:
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
因此,您可以在插入和删除行后调用它。 但是,如果您的count字段仅取决于您的表,我建议您进行触发,以重新计算您的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.