【问题标题】:Recursively update values based on rows parent id SQL Server基于行父 id SQL Server 递归更新值
【发布时间】:2013-08-03 02:27:29
【问题描述】:

我有如下表结构

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

【问题讨论】:

  • 你在使用 Linq-to-SQL 吗?
  • 我不是没有,只是使用SQLCommands
  • 我建议使用 CTE 来处理这个问题。

标签: c# asp.net sql-server sql-server-2008 recursion


【解决方案1】:

如果您真的只想更新计数,您可能需要编写存储过程来执行此操作:

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

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

【讨论】:

    【解决方案2】:

    您想为此使用递归 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-06
      • 2014-05-19
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 2023-01-12
      • 1970-01-01
      相关资源
      最近更新 更多