Update a column with values which its parent have.

Say we have a Table (Product)
ProductID, ProductName, IntParentID, IntCategoryID.

With the script below the intCategoryid of Parent  will become the intCategoryID of Child.

;with cte as
(
select intCategoryId, intProductID
from Product where intCategoryId is not null and intProductID is not null
union all
select cte.intCategoryId, t.intProductID
from Product t
join cte
on t.intParentCategory = cte.intProductID
and t.intCategoryId is null
)
update t
set t.intCategoryId = cte.intCategoryId
from Product t
join cte
on t.intProductID = cte.intProductID
option (maxrecursion 5000)

Comments

Popular posts from this blog

Grouping Sets, With Rollup and With Cube example

Adding Page brake aganist group values

To Get All the Names of tables and Databases their data have changed in last 24 Hours And Backup those databases