Considering the following source data:
| Id | Email | PhoneNumber |
+----+----------+-------------+
| 1 | p@q.com | 1231231234 |
| 2 | a@b.com | 9876543210 |
| 3 | x@y.com | 1231231234 |
| 4 | x@y.com | 5551231234 |
| 5 | l@m.com | 5559876543 |
| 6 | c@d.com | 9876543210 |
| 7 | p@q.com | 5555555555 |
| 8 | y@z.com | 5554443333 |
| 9 | e@f.com | 5555555555 |
I need a recursive SQL statement that will take a starting email and search all rows that are related to the given email and associated phone numbers.
For example, if the initial search Email is x@y.com then the results should return
| Id | Email | PhoneNumber |
+----+----------+-------------+
| 3 | x@y.com | 1231231234 |
| 4 | x@y.com | 5551231234 |
| 1 | p@q.com | 1231231234 |
| 7 | p@q.com | 5555555555 |
| 9 | e@f.com | 5555555555 |
So,
- x@y.com has 2 associated phone numbers ( 1231231234 & 5551231234 )
- phone number 1231231234 also is associated to email p@q.com
- p@q.com has 2 associated phone numbers ( 1231231234 & 5555555555 )
- phone number 5555555555 also is associated to email e@f.com
Thanks in advance for your consideration.
=============================================================== I have tried different ways and most were running away and getting the error
The statement terminated. The maximum recursion 100 has been exhausted before statement completion.
The following is what I had before putting this question in...
DECLARE @SourceData TABLE (
Id INT IDENTITY(1,1),
Email VARCHAR(255),
PhoneNumber VARCHAR(10)
)
INSERT INTO @SourceData ( Email, PhoneNumber )
VALUES
('p@q.com', '1231231234'),
('a@b.com', '9876543210'),
('x@y.com', '1231231234'),
('x@y.com', '5551231234'),
('l@m.com', '5559876543'),
('c@d.com', '9876543210'),
('p@q.com', '5555555555'),
('y@z.com', '5554443333'),
('e@f.com', '5555555555')
DECLARE @inEmail VARCHAR( 255 ) = 'x@y.com';
;WITH cteEmailPhone AS (
SELECT DISTINCT
Email,
PhoneNumber
FROM @SourceData
WHERE Email = @inEmail
UNION ALL
SELECT
a.Email,
a.PhoneNumber
FROM cteEmailPhone a
JOIN @SourceData b ON b.PhoneNumber = a.PhoneNumber
WHERE a.PhoneNumber <> b.PhoneNumber
)
SELECT *
FROM cteEmailPhone;