CREATE TABLE #Transfer( ID INT IDENTITY PRIMARY KEY, OldKey INT, NewKey INT)INSERT INTO #Transfer (OldKey, NewKey)VALUES (1, 2)INSERT INTO #Transfer (OldKey, NewKey)VALUES (2, 3)INSERT INTO #Transfer (OldKey, NewKey)VALUES (3, 4)INSERT INTO #Transfer (OldKey, NewKey)VALUES (5, 6)INSERT INTO #Transfer (OldKey, NewKey)VALUES (6, 7)
ID OldKey NewKey1 1 22 2 33 3 44 5 65 6 7
SELECT 1 AS OldKey, 4 AS NewKeyUNIONSELECT 2 AS OldKey, 4 AS NewKeyUNIONSELECT 3 AS OldKey, 4 AS NewKeyUNIONSELECT 4 AS OldKey, 4 AS NewKeyUNIONSELECT 5 AS OldKey, 7 AS NewKeyUNIONSELECT 6 AS OldKey, 7 AS NewKeyUNIONSELECT 7 AS OldKey, 7 AS NewKey
OldKey NewKey1 42 43 44 45 76 77 7
CREATE TABLE #Transfer( ID INT IDENTITY PRIMARY KEY, OldKey INT, NewKey INT)INSERT INTO #Transfer (OldKey, NewKey)VALUES (1, 2)INSERT INTO #Transfer (OldKey, NewKey)VALUES (2, 3)INSERT INTO #Transfer (OldKey, NewKey)VALUES (3, 4)INSERT INTO #Transfer (OldKey, NewKey)VALUES (5, 6)INSERT INTO #Transfer (OldKey, NewKey)VALUES (6, 7);WITH Transfers AS ( SELECT Oldkey=Newkey, Newkey FROM #Transfer UNION ALL SELECT a.Oldkey, a.Newkey FROM #Transfer a UNION ALL SELECT b.Oldkey, a.Newkey FROM Transfers a JOIN #Transfer b ON b.NewKey = a.Oldkey )SELECT OldKey, NewKey=MAX(NewKey)FROM TransfersGROUP BY OldKeyORDER BY OldKey, NewKeyDROP TABLE #Transfer