Sunday, March 25, 2012

bulk insert which check if record exists

Hi All,
I want to bulk insert from table A to table B (both table have the same
design fields which contain primary keys). Is there a way to check if record
exist before inserting rows to avoid primary key violation? What would be my
query?
thanks in advance,
joelTry something like this:
insert tableA (<cols> )
select b.<cols>
from tableA b
left outer join tableA a
on b.PrimaryKey = a.PrimaryKey
where a.PrimaryKey IS NULL|||If you assume that ID is your PK then you can do something like this
INSERT INTO TABLEB
SELECT A.*
FROM TABLEA A
LEFT JOIN TABLEB B
ON A.ID = B.ID
WHERE B.ID IS NULL
http://sqlservercode.blogspot.com/|||Sorry, tableA and tableB are backwards in my example. This will insert
into tableA, rows that are in tableB and not in tableA.
insert tableB (<cols> )
select a.<cols>
from tableA a
left outer join tableB b
on b.PrimaryKey = a.PrimaryKey
where b.PrimaryKey IS NULL|||Sorry again, untested code bites again.
This will insert
into tableB, rows that are in tableA and not in tableB.
insert tableB (<cols> )
select a.<cols>
from tableA a
left outer join tableB b
on b.PrimaryKey = a.PrimaryKey
where b.PrimaryKey IS NULLsql

No comments:

Post a Comment