2

我有一张桌子

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。

4

1 回答 1

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
于 2013-06-26T10:23:28.447 回答