S7H
S7H

Reputation: 1635

Copy data from one table to another iff second table doesn't already contains that data

Could any one help me in writing a MS SQL query to copy rows from one table to another only if table1.Col1 != table2.col1.

I am making a SSIS package to do this procedure so an approach related to it would be very helpful.

Upvotes: 0

Views: 73

Answers (2)

sandeep rawat
sandeep rawat

Reputation: 4957

1) Slowly Changing Dimension data flow task.

2) Use Lookup.

3) Use Merge.

Upvotes: 1

Doug Ivison
Doug Ivison

Reputation: 31

Simplest way (to me): optionally join (LEFT OUTER JOIN) to the target table (table you're loading into), and use WHERE to confirm that the join fails:

INSERT INTO dbo.MYTARGETTABLE (TARG_COL1, TARG_COL2)
SELECT SRC.[SRC_COL1], SRC.[SRC_COL2]
FROM dbo.MYSOURCETABLE  SRC
    LEFT OUTER JOIN dbo.MYTARGETTABLE  TARG
        ON TARG.[TARG_COL1] = SRC.[SRC_COL1]
WHERE SRC.[SRC_COL1] IS NOT NULL
----this column is only null if the join failed: 
AND TARG.[TARG_COL1] IS NULL

This of course assumes that there are no valid NULLs in the column(s) you join with.

Upvotes: 1

Related Questions