I have the following example table:
Each customer_number may have one or several debtor_id, and vice versa each debtor_id may have one or more customer_numbers. Now I basically need a way to retrieve all customer_numbers or debtor_ids from any given customer_number or debtor_id
A more specific example:
Say you want to know all customer_numbers that are connected to the debtor_id 24.
- Step1: debtor_id 24 is connected to customer_number customer12
- Step2: customer_number customer12 is connected to debtor_id 23 and 24 (the starting point)
- Step3: debtor_id 23 is connected to customer_number customer12 and customer11
- Step4: customer_number customer11 is connected to debtor_id 22 and 23 etc.
So in the end when inputting the debtor_id 24, you'd expect to retrieve the customer_number customer10, customer11 and customer12 as a result.
I know it'll probably require several self-joins, but it needs to be flexible and work dynamically for any given "depth". My first thought was that this heavily smells like recursion. Basically something like "keep self-joining until there are no new customer_numbers or debtor_id returned"
I don't have much experience with recursion, same goes for writing SQL Functions :-(
Does anybody have some tips or helpful advice on this?
Example code to generate the same table:
DECLARE @customers TABLE
(
customer_number VARCHAR(16),
debtor_id INT
);
INSERT INTO @customers SELECT 'customer10', 20;
INSERT INTO @customers SELECT 'customer10', 22;
INSERT INTO @customers SELECT 'customer11', 22;
INSERT INTO @customers SELECT 'customer11', 23;
INSERT INTO @customers SELECT 'customer12', 23;
INSERT INTO @customers SELECT 'customer12', 24;
INSERT INTO @customers SELECT 'customer15', 30;
INSERT INTO @customers SELECT 'customer16', 31;
INSERT INTO @customers SELECT 'customer16', 32;
INSERT INTO @customers SELECT 'customer21', 31;
INSERT INTO @customers SELECT 'customer21', 35;
SELECT *
FROM @customers;