How to avoid import duplicates in any columns while not using cursor?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cuqsy0
    New Member
    • Apr 2012
    • 22

    How to avoid import duplicates in any columns while not using cursor?

    In my project, I have two tables, looks like these:

    Table T1
    ----------
    Col1 , Col2

    1 , 2
    4 , 5
    8 , 9

    Table T2
    ----------
    Col1 , Col2

    2 , 1
    3 , 6
    0 , 5

    I wish to generate a new table (T3) from table T1, which only includes the row whose value in any columns does not exists in any columns of table T2. For this example, the final result should be:

    Table T3
    ----------
    Col1 , Col2
    8 , 9

    Note that the row (1,2) in T1 is not imported because 2 in the second column of T1 equals to 2 in the first column in the first row of T2. The row (4,5) in T1 is also not imported because 5 in the second column of T1 equals to 5 in the first column of third row of T2.

    It is easy to use a cursor T SQL to do this, but it is very time consuming for data set larger than 10000 for T1 and 1000 for T2, as I tried in my T-SQL test.

    Is these any more efficient way to do this?

    Thanks a lot.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Left join the first table to the union of both columns in the second table. Do that for each field and the one that returns null on both joins are the rows you want.

    Comment

    Working...