Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Tree Query with Hierarchyid
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

22 Posts

Posted - 02/22/2014 :  05:29:29  Show Profile  Reply with Quote
I have problem with tree query where if qty > 1 the result is fail.
Could someone explain me how to solve this problem.
Here's the code :

declare @BOMStructure as table  
PartNumber varchar(14)not null ,
Descript varchar(50)not null,
Qty integer not null default 0,
Price Decimal (10,2) default 0,
ItemNumber hierarchyid not null primary key 

INSERT @BOMStructure 
(PartNumber ,Descript ,Qty ,Price ,ItemNumber)
VALUES	('00150060060005','BASIC TANK',1,0,'/'),
		('12052140503','TOP CONE',1,0,'/2/'),
		('13052140503','BOTTOM CONE',2,100,'/2/1/'),
		('140104116508','PIPE LEG',3,50,'/2/2/'),
		('1524809510','ADJUSTABLE BOLT',1,100,'/3/1/'),
-- GetAncestor
-- Mengupdate 
select  PartNumber, Descript,Qty,Price,
			(select sum (Price * qty)
               from @BOMStructure
               where ItemNumber .IsDescendantOf (p.ItemNumber ) = 1
              ) as [TotalPrice], 
        ItemNumber .ToString() as [Hierarcy], ItemNumber .GetLevel() as [Level]
from @BOMStructure as P;

Yak Posting Veteran

75 Posts

Posted - 02/23/2014 :  20:53:47  Show Profile  Reply with Quote
What is your expected result?
At Intermediate node, multiply Qty together sum of child node's TotalPrice, like following?

WITH Work (PartNumber, Descript, Qty, Price, SubTotalPrice, ItemNumber) AS (
	SELECT PartNumber, Descript, Qty, Price, Price * Qty, ItemNumber
	FROM @BOMStructure Base
		SELECT * FROM @BOMStructure Filter
		WHERE Filter.ItemNumber.GetAncestor(1) = Base.ItemNumber)
	SELECT Base.PartNumber, Base.Descript, Base.Qty, Base.Price, Convert(Decimal(10, 2), Work.SubTotalPrice) * Base.Qty, Base.ItemNumber
	FROM @BOMStructure Base
		ON Work.ItemNumber.GetAncestor(1) = Base.ItemNumber
SELECT PartNumber, Descript, Qty, Price, SUM(SubTotalPrice) TotalPrice, ItemNumber.ToString() [Hierarcy], ItemNumber.GetLevel() [Level] FROM Work
GROUP BY PartNumber, Descript, Qty, Price, ItemNumber
ORDER BY ItemNumber

From Japan
Sorry, my English ability is limited.
Go to Top of Page

Starting Member

22 Posts

Posted - 02/24/2014 :  23:19:10  Show Profile  Reply with Quote

Thanks for your time and script.
Case closed :)
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.02 seconds. Powered By: Snitz Forums 2000