you need to use recursive CTE as belowCREATE PROC GetTotalQty@PID intAS;With CTEAS(SELECT ID,Qty,PID,CAST(ID AS varchar(max)) AS [Path]FROM TableWHERE PID = @PIDUNION ALLSELECT t.ID,t.Qty,t.PID,CAST(c.[Path] + ',' + CAST(t.ID AS varchar(50)) AS varchar(max))FROM CTE cINNER JOIN Table tON t.PID = c.ID)SELECT @PID AS PID,SUM(Qty) AS Total,MAX([path]) AS MaxPathFROM CTEOPTION (MAXRECURSION 0)GO
------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs