Corinne_09
asked on
Why is it saying "unique constraint violated"?
I am copying a table from one database to another i.e. ACCOUNTING.EXPENSES to FINANCING.EXPENSES
I want to maintain the primary keys (column 'ID') so I have my triggers off. However when I proceed to copy my tables it kept saying 'unique constraint violated' on the primary keys.
I don't know what's wrong with it. Pls help. Thanks.
I want to maintain the primary keys (column 'ID') so I have my triggers off. However when I proceed to copy my tables it kept saying 'unique constraint violated' on the primary keys.
I don't know what's wrong with it. Pls help. Thanks.
INSERT INTO FINANCING.EXPENSES (ID, EMPLOYEE_ID, AMOUNT, DATE_ENTERED, DESCRIPTION, ACTUAL_INVOICE_RATE)
SELECT ID, EMPLOYEEID, AMOUNT, DATE, COMMENTS, RATE
FROM ACCOUNTING.EXPENSES
WHERE EMPLOYEEID = 12345;
ASKER
The reason why I'm asking this question is because FINANCING.EXPENSES is an empty table, so there is no way the PK constraint is being violated if I'm just inserting new values. Also, both FINANCING.EXPENSES and ACCOUNTING.EXPENSES have a PK constraint enabled, so I don't understand why there would be duplicated keys in ACCOUNTING.EXPENSES in the first place.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
or there are triggers on the inserted table doing some other inserts to other tables which creates problem... did you check FINANCING.EXPENSES? maybe there are some active insert triggers...
or run this query to see whether the query returns duplicate data
or run this query to see whether the query returns duplicate data
SELECT ID, COUNT (*) rec_count
FROM accounting.expenses
-- WHERE employeeid = 12345 -- remove comment to see all duplicate data
GROUP BY ID
HAVING COUNT (*) > 1;
ASKER
All the primary keys are unique and all triggers were disabled. There was an issue with case-insensitive data so any difference in lowercase and uppercase values were treated differently, thus causing duplicate values.
means that either you copy duplicated key values, OR at least 1 row of the inserted data has a primary key value that is already in the destination table.
to solve, you need to either use the MERGE statement, or put a LEFT JOIN + WHERE to discard the rows that are already present, and eventually add a UPDATE statement (best before the insert) to do the updates, if needed (=> or as said, use the MERGE statement instead):
http://www.psoug.org/reference/OLD/merge.html