So i think you aught to change your schema so this query isn't the most ideal way of going about this im sure. I can think of a way of doing this while looping over each row and storing the results which would be slower than this also.
Basically it uses a join and a sub query to get the column1 + column2 matching results.
I get the same results as OP's original question but I don't get the same results as specified in the comment to my question. Manually doing the relationship i don't see how 18 can be a possible match for example.
DECLARE @Relationship TABLE (
Id INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
Column1 INT NULL,
Column2 INT NULL
);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (6,16);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (6,20);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (6,2);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (6,23);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (8,24);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (8,4);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (8,21);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (8,2);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (8,16);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (8,1);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (13,21);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (13,22);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (13,23);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (13,16);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (13,2);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (13,18);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (15,2);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (15,16);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (15,24);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (15,4);
INSERT INTO @Relationship ( Column1, Column2 ) VALUES (16,35);
DECLARE @Input INT = 6
SELECT DISTINCT A.Column2 AS Result1 FROM @Relationship AS A
LEFT OUTER JOIN @Relationship AS B ON B.Column1 = A.Column2
WHERE A.Column1 = @Input
UNION ALL
SELECT DISTINCT A.Column1 AS Result1 FROM @Relationship AS A
WHERE A.Column2 IN (SELECT DISTINCT A.Column2 FROM @Relationship AS A
LEFT OUTER JOIN @Relationship AS B ON B.Column1 = A.Column2
WHERE A.Column1 = @Input ) AND A.Column1 <> @Input
The above gives me the output of
Quote:
2
16
20
23
8
13
15