I have two tables, one is a Product Customer mapping and another is a Product sharing table. Using SQL recursive CTE, given a product, I am trying to find all the products that are linked as a chain, mapped across the customers. In addition, if a Product is shared with another Product, I need to include it in the chain too. Hopefully, my example make more sense than the description
Product Customer Table
Product Customer
Milk Illinois
Milk Michigan
Butter Michigan
Cream Wisconsin
Honey Wisconsin
Cheese Minnesota
Product Sharing Table
Product SharedProduct
Butter Cream
Cream Cheese
For the above data, let’s say my input Product is Milk, then the result set should include all the products – Milk, Butter, Cream, Honey & Cheese. Here Butter-Cream & Cream-Cheese are linked through the Product Sharing table.
My current SQL looks like this but doesn’t really work more than one level deep.
WITH Product_CTE AS
(
SELECT DISTINCT [Product] FROM ProductCustomer
WHERE [Product] IN (SELECT DISTINCT p2.[Product]
FROM ProductCustomer p1 INNER JOIN ProductCustomer p2
ON p1.[Customer] = p2.[Customer] WHERE p1.[Product] = 'Milk')
UNION ALL
SELECT [SharedProduct] FROM ProductSharing b
INNER JOIN Product_CTE p ON p.[Product] = b.[Product]
)
Select [Product] from Product_CTE
A CTE has issues with multiple
UNIONs. Although it may be possible, it wasn’t working for me.An alternative is to use a loop that stops when there are no more rows added to a working table:
Assumed herein is that the
@ProductSharingtable is unidirectional.