Hi @robert_volk , thanks for spending your precious time.
My bad i have not mentioned entire table scenario.
For example in table #tab
Insert into #tab
Select 'A','B' union all
Select 'A','C' union all
Select 'D','F' union all
Select 'D','G' union all
Select 'Z','E' union all
Select 'Z','S'
If you observe, one same SourceAccID is linked with two different DestinationAccID.
Similarly there will be millions of unique records in this way.
If i get an input as an 'S' i need to retrive 'Z' and 'E'
If i get an input as an 'Z' i need to retrive 'S' and 'E'
If i get an input as an 'E' i need to retrive 'Z' and 'S'
If i get an input as an 'D' i need to retrive 'F' and 'G'
If i get an input as an 'F' i need to retrive 'D' and 'G'
If i get an input as an 'G' i need to retrive 'F' and 'D'
If i get an input as an 'B' i need to retrive 'A' and 'C
'If i get an input as an 'A' i need to retrive 'B' and 'C'
If i get an input as an 'C' i need to retrive 'A' and 'B'
DROP TABLE IF EXISTS #tab;
CREATE TABLE #tab (SourceAccID varchar(100) , DestinationAccID varchar(100));
INSERT INTO #tab
SELECT 'A','B' UNION
SELECT 'A','C' UNION
SELECT 'D','F' UNION
SELECT 'D','G' UNION
SELECT 'Z','E' UNION
SELECT 'Z','S';
DECLARE @AccID VARCHAR(100)
SET @AccID='B';
WITH FirstLevel AS
(
SELECT
SourceAccID,
DestinationAccID,
CASE WHEN DestinationAccID=@AccID THEN SourceAccID ELSE DestinationAccID END AS Result
FROM #tab
WHERE SourceAccID=@AccID OR DestinationAccID=@AccID
)
SELECT
FirstLevel.Result
FROM FirstLevel
UNION
SELECT
SecondLevel.DestinationAccID
FROM FirstLevel
INNER JOIN #Tab AS SecondLevel
ON FirstLevel.SourceAccID=SecondLevel.SourceAccID
WHERE SecondLevel.DestinationAccID <> @AccID;
thanks a lot for your time.
its working as expected.
if i do the below changes to query will it impact to the output ?
DECLARE @AccID VARCHAR(100)
SET @AccID='B';
WITH FirstLevel AS
(
SELECT
SourceAccID,
DestinationAccID,
CASE WHEN DestinationAccID=@AccID THEN SourceAccID ELSE DestinationAccID END AS Result
FROM #tab
WHERE SourceAccID=@AccID
UNION ALL
SELECT
SourceAccID,
DestinationAccID,
CASE WHEN DestinationAccID=@AccID THEN SourceAccID ELSE DestinationAccID END AS Result
FROM #tab
WHERE DestinationAccID=@AccID
)
SELECT
FirstLevel.Result
FROM FirstLevel
UNION
SELECT
SecondLevel.DestinationAccID
FROM FirstLevel
INNER JOIN #Tab AS SecondLevel
ON FirstLevel.SourceAccID=SecondLevel.SourceAccID
WHERE SecondLevel.DestinationAccID <> @AccID;
Based on the example you gave it won't have any impact on the output as a SourceAccID <> DestinationAccID. To be sure you should test it yourself as I suspect a negative performance impact.