Click to See Complete Forum and Search --> : Unique INSERT INTO


fark
11-17-2003, 09:54 AM
strsql="INSERT INTO tempUPS (PkgPrimary, m_packageId, m_weight, m_packageType, m_oversizeType, Sm_trackingNo ) IN 'C:\temp.mdb' SELECT m_primaryKey, m_packageId, m_weight, m_packageType, m_oversizeType, Sm_trackingNo FROM calPackage;"

How do I tell the INSERT INTO Statement to only insert the new record if it is unique. If I run this statement once I have 1000 if I run it twice I have 2000. I don't want duplicates to be inserted but when something is added to the source database that isn't in the destination I want the destination to have have the new records inserted. I thought about using update but that only updates the reccord it doesn't add a new one. I tried using DISTINCTROW with my INSERT INTO but then I get a syntax error. I set my indexing in the database not to accept duplicates but then it stops at the first duplicate with an error and doesn't add the new ones. I'm kinda stumped and don't know what to try next. Thanks for you help.

fark
11-17-2003, 10:12 AM
In my search for an answer to my question I came across this.

-- Transaction A
DROP TABLE foo;
CREATE TABLE foo (id INTEGER);
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN;
-- Transaction B
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN;
INSERT INTO foo (id) SELECT 1 WHERE NOT EXISTS (SELECT * FROM foo WHERE id
= 1);
COMMIT;
SELECT * FROM foo;
-- Transaction A
SELECT * FROM foo;
INSERT INTO foo (id) SELECT 1 WHERE NOT EXISTS (SELECT * FROM foo WHERE id
= 1);
SELECT * FROM foo;
COMMIT;

I'm not really sure what I'm looking at as I am still learning SQL. Does the WHERE NOT EXISTS apply to my question about unique inserts? I found this at
http://archives.postgresql.org/pgsql-general/2000-04/msg00583.php
Thanks again

CardboardHammer
11-24-2003, 06:02 AM
Yeah. Use WHERE NOT EXISTS and SELECT * WHERE all fields are exactly what you want to INSERT, if unique. If it's not there, WHERE NOT EXISTS is true and the INSERT happens, else it's false and no insertion takes place.