SQL 2005 SCRIPT to COMPARE

  • HI

    Please help, I need to write a script that will check two tables by a candidateID to see if any candidate are missing that are in Table1 that are not in table2 and then check the other way round.

    The (candidateID are unique) and may not be in the same row number. I need to identify the CandidateID so a count would not work.

    This is so I can import the missing candidates into both tables so they match.

    SQL 2005 standard clustered 9.0.3175

    I have been using distinct but it not give the right data.

    Thank for your help!

  • Something like this should work:

    SELECT T.CandidateID,

    Missing=CASE WHEN T1.CandidateID IS NULL THEN 'Missing From Table 1'

    WHEN T2.CandidateID IS NULL THEN 'Missing From Table 2'

    ELSE 'Present in Both'

    END

    FROM (SELECT DISTINCT CandidateID

    FROM TABLE1

    UNION ALL

    SELECT DISTINCT CandidateID

    FROM TABLE2) T

    LEFT JOIN Table1 T1 ON T.CandidateID = T1.CandidateID

    LEFT JOIN Table2 T2 ON T.CandidateID = T2.CandidateID

    Seth Phelabaum


    Consistency is only a virtue if you're not a screwup. 😉

    Links: How to Post Sample Data[/url] :: Running Totals[/url] :: Tally Table[/url] :: Cross Tabs/Pivots[/url] :: String Concatenation[/url]

  • I think the solution above should give you results. Left joins show nulls where something doesn't match.

  • SELECT T1.CandidateID, 'Missing From Table 2'

    FROM Table1 T1

    WHERE NOT EXISTS (select 1 from Table2 T2 where T1.CandidateID = T2.CandidateID)

    UNION ALL

    SELECT T2.CandidateID, 'Missing From Table 1'

    FROM Table2 T2

    WHERE NOT EXISTS (select 1 from Table1 T1 where T1.CandidateID = T2.CandidateID)

    _____________
    Code for TallyGenerator

  • Hi Would like to say thank you for the below code It worked great.

    SELECT T.CandidateID,

    Missing=CASE WHEN T1.CandidateID IS NULL THEN 'Missing From Table 1'

    WHEN T2.CandidateID IS NULL THEN 'Missing From Table 2'

    ELSE 'Present in Both'

    END

    FROM ( SELECT DISTINCT CandidateID

    FROM TABLE1

    UNION ALL

    SELECT DISTINCT CandidateID

    FROM TABLE2) T

    LEFT JOIN Table1 T1 ON T.CandidateID = T1.CandidateID

    LEFT JOIN Table2 T2 ON T.CandidateID = T2.CandidateID

    Thanks again.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply