Recursive SQL Query with Defined Start Point
14:35 03 Jul 2018

I'm trying to get a recursive query to work with a defined starting point.

Here's some sample data from my table called Part_v_Container:

Serial_No   From_Container  Part_Key    Part_Operation_Key
1234                1233    5678         5
1233                1232    5678         4
1231                1230    5678         3
1230                NULL    5678         2

Basically we ship a serial number and then I need to trace it back following all the previous serial numbers From_Container through the process. In my real query I'll have the starting Serial_No be a user defined variable.

Here's my attempt:

;WITH Recursive_cte AS
(SELECT 
  PContainer.Serial_No
  ,PContainer.From_Container
  ,PContainer.Part_Key
  ,PContainer.Part_Operation_Key
  
  FROM Part_v_Container AS PContainer
  WHERE Serial_No LIKE '1234'  -- Will be user defined variable
  
UNION ALL

SELECT 
    PContainer.Serial_No
    ,PContainer.From_Container
    ,PContainer.Part_Key
    ,PContainer.Part_Operation_Key  
  FROM Recursive_cte
  INNER JOIN
  Part_v_Container AS PContainer
  ON PContainer.From_Container = Recursive_cte.Serial_No 
  )
 
 SELECT * 
 FROM Recursive_cte

Yet this only returns one row, the Serial_No = 1234 row. My real data set has thousands of serial numbers and I need to be able to pick which ones I pick from to trace back, not a broad query that is recursive for every one in my table.

I've tried reading several articles and examples to get this to work, including the one here with no success.

sql-server sql-server-2012 recursive-query