【问题标题】:How to skip same duplicate key data when copy table [duplicate]复制表时如何跳过相同的重复键数据[重复]
【发布时间】:2017-06-28 05:34:49
【问题描述】:

我有一个 table1(key is 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

【问题讨论】:

  • 那个答案有同样的错误Error report - SQL Error: ORA-00001: unique constraint (table2_index) violated 00001. 00000 - "unique constraint (%s.%s) violated" *Cause: An UPDATE or INSERT statement attempted to insert a duplicate key. For Trusted Oracle configured in DBMS MAC mode, you may see this message if a duplicate entry exists at a different level. *Action: Either remove the unique restriction or do not insert the key.
  • 那么您需要查看 ON 标准,因为您的标准不够严格,无法满足 UNMATCHED 过滤器的要求。
  • 我通过INSERT /*+ ignore_row_on_dupkey_index(table2, table2_index) */ INTO table2 (code, name, xx, yy, xxx, yyy) SELECT x, y, xx, yy, xxx, yyy FROM table1得到了我需要的东西

标签: oracle subquery sql-insert sqlbulkcopy


【解决方案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)

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

【讨论】:

  • 我得到了同样的错误:(
  • 我得到了我需要的东西INSERT /*+ ignore_row_on_dupkey_index(table2, table2_index) */ INTO table2 (code, name, xx, yy, xxx, yyy) SELECT x, y, xx, yy, xxx, yyy FROM table1
  • 你可以勾选答案为正确
【解决方案2】:

你可以试试光标:

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;
/

【讨论】:

  • 可以不用光标吗?
  • 错误CURSOR c1 IS SELECT Error report - Unknown Command
  • 如果您不想使用游标,请在下面使用:BEGIN FOR insertValue IN (SELECT code, name, xx, yy, xxx, yyy from table1) LOOP insert into table2(code, name, xx, yy, xxx, yyy) 值(insertValue.code, insertValue.name,insertValue.xx ...);结束循环;结尾; /
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
相关资源
最近更新 更多