Mombu the Microsoft Forum sponsored links

Go Back   Mombu the Microsoft Forum > Microsoft > Help Primary Key violation
User Name
Password
REGISTER NOW! Mark Forums Read

sponsored links


Reply
 
1 1st August 23:01
andrea
External User
 
Posts: 1
Default Help Primary Key violation



I'm trying to port access DB to Sql Server database.
With access I can insert several rows also if someone are present in the
destination table.
For example if I have 20 rows in the dest table and I want to insert 30 rows
from orig table to dest table, but 20 rows are present in the dest table, an
insert command, will insert the 10 new rows and return a message of primary
key violation.

Sql Server, return primary key violation message, but don't insert the new
10 rows.
How can I do?
The problem is that the destination table have 3.000.000 of records and
source table have 400.000 record.

Thanks for your help.

Andrew
  Reply With Quote


  sponsored links


2 1st August 23:02
andrew j. kelly
External User
 
Posts: 1
Default Help Primary Key violation



Well I wouldn't recommend doing all the inserts in one batch as it may take
a while and probably grow your tran log quite a bit. But you can use NOT
EXISTS to do this.

INSERT INTO TableA (PK, Col2, Col3...)
SELECT b.PK, b.Col2, b.Col3.. FROM TableB AS b
WHERE NOT EXISTS (SELECT * FROM TableA AS a WHERE a.PK = b.PK)

Or you could remove the duplicates first and then just Insert.

--

Andrew J. Kelly
SQL Server MVP
  Reply With Quote
3 1st August 23:02
andrea
External User
 
Posts: 1
Default Help Primary Key violation


Thanks Andrew,
do you think is better use NOT EXISTS or use LEFT JOIN where the right row
is null?
This is the example:

INSERT INTO TableA (PK, Col2, Col3...)
SELECT b.PK, b.Col2, b.Col3..
FROM TableB AS b LEFT JOIN TableA ON b.PK=TableA.PK
WHERE TableA.PK IS NULL

Which is faster?
Thanks again.

"Andrew J. Kelly" <sqlmvpnooospam@shadhawk.com> ha scritto nel messaggio
news:uBqjjg18DHA.712@tk2msftngp13.phx.gbl...

take
  Reply With Quote
4 1st August 23:02
andrew j. kelly
External User
 
Posts: 1
Default Help Primary Key violation


EXISTS will usually be as fast or faster in almost all cases but it always
pays to test for your particular conditions.
--

Andrew J. Kelly
SQL Server MVP
  Reply With Quote
Reply


Thread Tools
Display Modes




Copyright © 2006 SmartyDevil.com - Dies Mies Jeschet Boenedoesef Douvema Enitemaus -
666