I am needing to create a result set of customers who are related by phone numbers.
The phone number records are stored in various tables within the database. I have already consolidated the phone record information and it creates a temp table (currently about 1.3 million distinct customerID, phone numbers).
From this temp table (a temp table needs to be used for various reason and at this stage it is not in my control), I need to find all connected customers by phone.
Example:
customer 'A' at somepoint listed a phone number that matches customer 'B', 'C', and 'D'.
I am doing this with:
DECLARE @CustomerID INT = 1
IF OBJECT_ID('tempdb..#e') IS NOT NULL
DROP TABLE #e
CREATE TABLE #e (CustomerID int, phone bigint)
INSERT INTO #e
values
(1,5551234456)
,(2,5551234456)
,(2,5551237789)
,(3,5551237789)
,(3,5551231123)
,(3,5552341212)
,(4,5552341213)
,(4,5551234456)
,(4,5551237789)
,(4,5551231123)
,(5,5551234567)
,(6,5559874561)
SELECT P.*, @CustomerID AS connection_customer_id
FROM #e AS P
WHERE 1 = 1
AND P.phone IN (
SELECT phone
FROM #e
WHERE #e.CustomerID = @CustomerID
)
AND P.CustomerID <> @CustomerID;
But, I need this to loop through the result set and continue the loop through any Customer that has not already been researched.
In the above Example, the desired result would be:
CustomerID phone connection_customer_id
2 5551234456 1
4 5551234456 1
3 5551237789 2
4 5551234456 2
4 5551237789 2
4 5551237789 3
4 5551231123 3
What is the most efficient way to do this?
Thank you for any help on this.
--- Update
Updated code and expected results to add clarity.