2013-08-01 51 views
0

我有以下表结构递归更新值

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

+0

你正在使用Linq-to-SQL? – ataravati

+0

我不是,只是使用SQLCommands – opdb

+0

我建议使用CTE来处理这个问题。 – tsells

回答

0

如果你真的想只更新数,你可以想写的存储过程可以这样做:

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 

SQL FIDDLE EXAMPLE

所以,你可以把它插入和删除行之后。但是,如果你的计数字段只取决于你的表格,我会建议做一个触发器,它将重新计算你的值

+0

非常优雅和易于使用,谢谢。 – opdb

0

你想使用递归的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