简体   繁体   中英

Recursively update values based on rows parent id SQL Server

I have the following table structure

| id | parentID | count1 |

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

I increase count values from my source code, but i also need the increase in value to bubble up to each parent id row until the parent id is -1.

eg. If I were to increase count1 on row ID #6 by 1, row ID #5 would increase by 1, ID #3 would increase by 1, and ID #2 would increase by 1.

Rows also get deleted, and the opposite would need to happen, basically subtracting the row to be deleted' value from each parent.

Thanks in advance for your insight.

I'm using SQL Server 2008, and C# asp.net.

You want to use a recursive CTE for this:

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);

Here is the SQL Fiddle .

If you really want to just update counts, you could want to write stored procedure to do so:

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

So you could call it after you insert and delete rows. But if your count field are depends just on your table, I would suggest to make a triggers which will recalculate your values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM