如何在复制表时跳过相同的重复键数据

时间:2017-06-28 05:34:49

标签: oracle subquery sql-insert sqlbulkcopy

我有一个table1(键是X,XX)如下所示:

x,y,xx,yy,xxx,yyy

我创建了一个新的table2(键是代码),如下所示:

code,name,xx,yy,xxx,yyy

现在我要将table1中的所有数据复制到table2,如果遇到相同的代码则跳过它,

x -> code
Y -> name
xx-> xx
yy -> yy
xxx -> xxx
yyy -> yyy

我使用下面的代码复制所有数据,我收到错误00001. 00000 - "unique constraint (%s.%s) violated",因为table1中有重复的x,但我不知道如何跳过重复的X数据,你能帮助我吗?

INSERT INTO table2 (code, name, xx, yy, xxx, yyy) 
SELECT x, y, xx, yy, xxx, yyy FROM table1

我试过这个,我觉得这不对。

INSERT INTO table2 (code, name, xx, yy, xxx, yyy) 
SELECT DISTINCT x, y, xx, yy, xxx, yyy FROM table1

2 个答案:

答案 0 :(得分:1)

试试这个:

INSERT INTO table2 (code, name, xx, yy, xxx, yyy) 
SELECT DISTINCT x, y, xx, yy, xxx, yyy FROM table1
where x not in (select code from table2)

OR

使用提示/*+ ignore_row_on_dupkey_index(table2, table2_index) */

答案 1 :(得分:0)

您可以尝试使用光标:

DECLARE
Cursor c1 is select code, name, xx, yy, xxx, yyy from table1;

for insertValue in c1
loop

insert into table2(code, name, xx, yy, xxx, yyy) values (insertValue.code, insertValue.name,insertValue.xx ... );

end loop;

由于重复,插入很少会失败,但应插入休息。

或没有光标的其他选项是:

BEGIN
 FOR insertValue IN (
 select code, name, xx, yy, xxx, yyy from table1 )
LOOP
insert into table2(code, name, xx, yy, xxx, yyy) values (insertValue.code, 
insertValue.name,insertValue.xx ... );  
END LOOP;
END;
/