2017-04-03 380 views
0

我必須將數據插入到表,但這個表有兩列column_1column_2唯一約束。現在在插入過程中出現以下錯誤:避免重複在插入

Lookup Error - DB2 Database Error: ERROR [23505] [IBM][DB2/AIX64] SQL0803N One or more values in the INSERT statement, UPDATE statement, or foreign key update caused by a DELETE statement are not valid because the primary key, unique constraint or unique index identified by "1" constrains table "table_name" from having duplicate values for the index key. SQLSTATE=23505.

如何避免此錯誤?

+1

請參閱https://www.withdata.com/blog/db2/replace-update-or-insert-a-row-into-db2-table-merge-into.html –

回答

0

最後,我使用NOT EXISTS子句來處理solvit。

1

您可以實現「upsert = update或insert」語義。

MERGE INTO employees AS tab 
USING (VALUES 
     (123456,'smith','bob') 
    ) AS merge (id,last_name,first_name) 
    ON tab.id = merge.id 
    WHEN MATCHED THEN 
     UPDATE SET tab.id = merge.id, 
        tab.last_name = merge.last_name, 
        tab.first_name = merge.first_name 
    WHEN NOT MATCHED THEN 
     INSERT (id,last_name,first_name) 
     VALUES (merge.id, merge.last_name, merge.first_name) 
1

雖然做插入只檢查那些列值是否已經存在於表中或沒有,如果不是則不會插入否則:在DB2中,這可以以下面的方式(例如,從here截取)來實現給出任何結果。

Insert into yourtable(required columns or u can omit if all) 
Select ur columns from othertable where (column1,column2) not in 
(Select column1,column2 from yourtable) 
+0

我已經使用not exists命令,但感謝它也有幫助。 – lukesky