2013-06-26 75 views
2

我有一個表更新記錄基於父ID

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 

我想更新我也想有一個值其父更新intCategoryId具有intcategory id爲null這行的intcategory ID(intParentCategory )有。

例如intproductid 3有intparentid 1,所以我想爲它的父母有intproductid 3 intcategoryid 3。

回答

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 
+0

沒有將更新整個樹,它不是像 我想與其父有intcategoryid的值更新intcategoryid .. 。geting我的poiint? –

+1

@MuhammadJawad是不是正是我所做的?如果沒有請更改您的帖子以包含預期數據 –

+0

家長的intcategoryID將成爲孩子的intcaregoryid。我想相應更新 –