Question : TSQL nested WHILE EXISTS

Hi experts,
My WHILE EXISTS loop never exit.
Can you help me with this?

@Parent_ID

DECLARE @Child_ID int

WHILE EXISTS(SELECT InventorytID, ParentID FROM Table WHERE ParentID = @Parent_ID)
BEGIN
         SELECT @Child_ID = InventorytID FROM Table WHERE ParentID = @Parent_ID
         --return the content of the first while loop

         --start second loop
         WHILE EXISTS(SELECT InventorytID, ParentID FROM Table WHERE ParentID = @Child_ID)
         BEGIN
         --return the content of the second while loop
         END
END

Answer : TSQL nested WHILE EXISTS

If you want to travers a table - like a Bill Of Materials table, then you can use a recursive CTE type query starting at @parent and then return the complete bill.

Does that sound a bit like what you are trying to do ?

By way of example, using a temp table instead (just for the example - you use your real table name)


create table #table (parentid int, inventoryID int, inventory_name varchar(100))
insert #table values (1,0,'Parent1')
insert #table values (1,2,'Parent1Child2')
insert #table values (2,3,'Parent2Child3')
insert #table values (3,0,'Parent3')

-- now we have some sampel data, the CTE recursive query

;with BOM_CTE as
(SELECT InventoryID, ParentID, inventory_name
 FROM #Table
 WHERE ParentID = 1

 union all

 SELECT T.InventoryID, T.ParentID, T.inventory_name
 FROM #Table T
 INNER JOIN BOM_CTE C on T.ParentID = C.InventoryID
 )
select parentid, inventoryid as child_id, inventory_name from BOM_CTE
Random Solutions  
 
programming4us programming4us