Home All Groups Group Topic Archive Search About

How to inser unique record into a table?



Author
9 Jul 2009 4:29 PM
aspfun via SQLMonster.com
How to inser unique record into a table?
Table A has a primary key in MemberID. I used code below but got error said

Violation of PRIMARY KEY constraint 'PK_ID'. Cannot insert duplicate key in
object 'A'

INSERT INTO A(MemberID)
SELECT MEMBID FROM B
where B.MEMBID not in (select MemberID from A)


Author
9 Jul 2009 4:42 PM
Tom Cooper
Does B have duplicate MEMBID's.  If so, that can cause this error.

Tom

"aspfun via SQLMonster.com" <u53138@uwe> wrote in message
news:98d2c9484d598@uwe...
Show quoteHide quote
> How to inser unique record into a table?
> Table A has a primary key in MemberID. I used code below but got error
> said
>
> Violation of PRIMARY KEY constraint 'PK_ID'. Cannot insert duplicate key
> in
> object 'A'
>
> INSERT INTO A(MemberID)
> SELECT MEMBID FROM B
> where B.MEMBID not in (select MemberID from A)
>
> --
> Message posted via SQLMonster.com
> http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200907/1
>
Are all your drivers up to date? click for free checkup

Author
9 Jul 2009 5:16 PM
Plamen Ratchev
Tom answered what could be the problem, you can fix it like this:

INSERT INTO A(memberid)
SELECT DISTINCT membid
FROM B
WHERE NOT EXISTS(SELECT *
                  FROM A
                  WHERE A.memberid = B.membid);

or this:

INSERT INTO A(memberid)
SELECT membid FROM B
EXCEPT
SELECT memberid FROM A;

--
Plamen Ratchev
http://www.SQLStudio.com
Author
9 Jul 2009 5:10 PM
Rick Sawtell
"aspfun via SQLMonster.com" <u53138@uwe> wrote in message
news:98d2c9484d598@uwe...
Show quoteHide quote
> How to inser unique record into a table?
> Table A has a primary key in MemberID. I used code below but got error
> said
>
> Violation of PRIMARY KEY constraint 'PK_ID'. Cannot insert duplicate key
> in
> object 'A'
>
> INSERT INTO A(MemberID)
> SELECT MEMBID FROM B
> where B.MEMBID not in (select MemberID from A)
>
> --
> Message posted via SQLMonster.com
> http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200907/1
>

Your B table may have multiple B.MEMBERIDs that are the same.

Try the following simple modification to your script:

INSERT INTO A(MemberID)
SELECT DISTINCT MEMBERID FROM B
where B.MEMBERID not in (select MemberID from A)


--  A better method is to use an EXISTS clause or a  join rather than the IN
statement.
INSERT INTO A(MemberID)
SELECT DISTINCT MemberID FROM b
WHERE NOT EXISTS (SELECT 1 FROM A JOIN B ON A.MEMBERID = B.MEMBERID)

-- Or in 2005, you can use an EXCEPT clause as well
INSERT INTO A(MemberID)
SELECT    DISTINCT MemberID FROM B
EXCEPT
SELECT MemberID FROM A


I hope this helps.

Rick Sawtell
MCT, MCSD, MCDBA, MCITPro

Bookmark and Share