• This WHILE LOOP might be a little cleaner and faster than what you've got and should resolve to any number of levels.

    DECLARE @increment TINYINT

    DECLARE @didinsert TINYINT

    /* create test data for person id combinations */

    CREATE TABLE #personIds(

    partykey INT

    ,personId INT

    )

    INSERT INTO #personIds

    SELECT 1, 1

    UNION ALL

    SELECT 2, 3

    UNION ALL

    SELECT 3, 1

    UNION ALL

    SELECT 3, 3

    UNION ALL

    SELECT 4, 4

    ;

    /* create test data for orders */

    CREATE TABLE #orders (

    orderId INT

    ,partykey INT

    )

    INSERT INTO #orders

    SELECT8829, 1

    UNION ALL

    SELECT 9323, 3

    UNION ALL

    SELECT 7321, 4

    ;

    /* to store all partykey combinations */

    CREATE TABLE #orderPartyIds (

    orderid INT

    ,partykey INT

    ,personid INT

    ,incrementNbr TINYINT

    )

    ;

    DECLARE @RowsCount INT, @Iteration INT = 1;

    INSERT INTO #orderPartyIDs (orderid, partykey, personid, incrementNbr)

    SELECT orderid, a.partykey, b.personid, @Iteration

    FROM #orders a

    JOIN #personIDs b ON a.partykey = b.partykey;

    SELECT @RowsCount = @@ROWCOUNT, @Iteration = @Iteration + 1;

    WHILE @RowsCount > 0

    BEGIN

    INSERT INTO #orderPartyIDs (orderid, partykey, personid, incrementNbr)

    SELECT orderid, partykey, personid, @Iteration

    FROM

    (

    SELECT a.orderid, b.partykey, b.personid

    FROM #orderPartyIDs a

    JOIN #personIDs b ON a.personid = b.personid OR a.partykey = b.partykey

    EXCEPT

    SELECT orderid, partykey, personid

    FROM #orderPartyIDs

    ) a;

    SELECT @RowsCount = @@ROWCOUNT, @Iteration = @Iteration + 1;

    END

    SELECT orderid, partykey, IncrementNbr

    FROM

    (

    SELECT orderid, partykey, IncrementNbr

    ,rn=ROW_NUMBER() OVER (PARTITION BY orderid, partykey ORDER BY IncrementNbr)

    FROM #orderPartyIDs

    ) a

    WHERE rn=1;

    GO

    /* clean up */

    DROP TABLE #personIds

    DROP TABLE #orders

    DROP TABLE #orderPartyIds

    Note that I added a column to your #orderPartyIDs temp table.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St