I have a table with self referencing relation,
ID  parentID UserId Title 
 1    null     100   A
 2     1       100   B
 3     2       100   C 
 4     2       100   D
 5     null    100   E
 6     5       100   F
I want to update UserId from 100 to 101 for all records with ID=1 and its children, so I want to have
ID  parentID UserId Title 
 1    null     101   A
 2     1       101   B
 3     2       101   C 
 4     2       101   D
 5     null    100   E
 6     5       100   F
How can I do it in T-SQL?
First, execute the anchor member to form the base result set (R0), use this result for the next iteration. Second, execute the recursive member with the input result set from the previous iteration (Ri-1) and return a sub-result set (Ri) until the termination condition is met.
Recursion is achieved by WITH statement, in SQL jargon called Common Table Expression (CTE). It allows to name the result and reference it within other queries sometime later. Naming the result and referencing it within other queries.
Recursion occurs because of the query referencing the CTE itself based on the Employee in the Managers CTE as input. The join then returns the employees who have their managers as the previous record returned by the recursive query. The recursive query is repeated until it returns an empty result set.
A recursive CTE references itself. It returns the result subset, then it repeatedly (recursively) references itself, and stops when it returns all the results. FROM cte_name; Again, at the beginning of your CTE is the WITH clause.
You probably want to use a common table expression which allows you to generate recursive queries.
eg:
;with cte as 
(
    select * from yourtable where id=1
    union all
    select t.* from cte 
        inner join yourtable t on cte.id = t.parentid
)
    update yourtable
    set userid = 101
    where id in (select id from cte)    
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With