gpt4 book ai didi

database - 根据父 ID 更新记录

转载 作者:搜寻专家 更新时间:2023-10-30 20:18:49 26 4
gpt4 key购买 nike

我有一张 table

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 的行的 intcategory id 为 null 我还想用其父级 (intParentCategory) 具有的值更新 intCategoryId。

例如 intproductid 3 有 intparentid 1,所以我想要 intcategoryid 3 作为其父级拥有的 intproductid 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

关于database - 根据父 ID 更新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17316647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com