• This is a bit tricky and I am still working on this. Here's what I have thusfar...

    --Create temp table to hold the dummy data

    if object_id('tempdb..#IDs') is not null

    drop table #IDs

    CREATE TABLE #IDs

    (

    InvoiceId int not null,

    BookingId int not null,

    primary key clustered (InvoiceId, BookingId)

    );

    INSERT #IDs VALUES (1,9), (1,10), (1,11), (2,11), (3,11), (3,12), (3,13), (4,14), (5,14)

    GO

    DECLARE @val int = 1;

    WITH x AS

    (

    SELECT i.InvoiceId, i.BookingId

    from

    (

    SELECT InvoiceId, BookingId

    from #IDs

    WHERE InvoiceId = @val

    ) a

    JOIN #IDs i ON a.BookingId = i.BookingId

    )

    SELECT DISTINCT i.*

    FROM x

    RIGHT JOIN #IDs i ON x.InvoiceId = i.InvoiceId

    WHERE x.InvoiceId IS NOT NULL

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001