0

我有以下表结构

| id | parentID | count1 |

  2      -1         1
  3       2         1
  4       2         0
  5       3         1
  6       5         0

我从我的源代码中增加计数值,但我还需要增加值以冒泡到每个父 ID 行,直到父 ID 为-1。

例如。如果我将count1行 ID #6 增加 1,行 ID #5 将增加 1,ID #3 将增加 1,ID #2 将增加 1。

行也被删除,相反的情况需要发生,基本上从每个父项中减去要删除的行的值。

提前感谢您的洞察力。

我正在使用 SQL Server 2008 和 C# asp.net。

4

2 回答 2

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 小提琴

于 2013-08-02T02:33:10.353 回答
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 提琴示例

因此,您可以在插入和删除行后调用它。但是,如果您的计数字段仅取决于您的表,我建议您创建一个触发器来重新计算您的值

于 2013-08-02T02:54:51.267 回答