我有一张桌子
intProductID vchProductName intParentCategory intCategoryId
1 Post Cards NULL 3
2 Packaging Boxe NULL 5
3 12- Page Booklets 1 NULL
4 16- Page Booklets 12 NULL
我想更新具有intcategory id的哪些行为null的intcategory id,我还想用其父(intParentCategory)具有的值更新intCategoryId。
例如intproductid 3有intparentid 1所以我想intcategoryid 3为intproductid 3,其父母有。
答案 0 :(得分:3)
update t1
set intcategoryID = t2.intCategoryId
from <table> t1
join <table> t2
on t1.intParentCategory = t2.intProductID
where t1.intCategoryId is null
这是一个带有测试表的解决方案,它将更新父层次结构的整个树
declare @t table(intProductID int, vchProductName varchar(20), intParentCategory int, intCategoryId int)
insert @t values(1, 'Post Cards',NULL,3),
(2,'Packaging Boxe', NULL,5),
(3,'12- Page Booklets', 1,NULL),
(4,'16- Page Booklets',12, NULL),
(5,'tst', 3, null)
--select intCategoryId, intProductID
--from @t where intCategoryId is not null and intProductID is not null
;with cte as
(
select intCategoryId, intProductID
from @t where intCategoryId is not null and intProductID is not null
union all
select cte.intCategoryId, t.intProductID
from @t t
join cte
on t.intParentCategory = cte.intProductID
and t.intCategoryId is null
)
update t
set t.intCategoryId = cte.intCategoryId
from @t t
join cte
on t.intProductID = cte.intProductID
option (maxrecursion 5000)
select * from @t