插入并选择Oracle:仅插入没有唯一约束违规的ID

时间:2014-03-20 13:50:24

标签: sql sql-server oracle oracle11g

我有两张表deparmentsdeparments_copy

SQL> select * from departments;
ID DESCRIPTION
 1 description1
 2 description2
 3 description3
 4 description4
 5 description5
 6 description6
 7 description7
 8 description8
 9 description9
10 description10
11 description11

SQL> select * from departments_copy;
ID DESCRIPTION
 1 description_copy1
 5 description_copy2
10 description_copy3

对于ID我有一个独特的约束:

alter table departments_copy add constraint pk_dp_copy primary key (id);

如果我使用oracle的insert into select语法,我将得到一个预期的唯一约束错误。是否可以使用insert select语法仅插入没有唯一约束违规的元素?

 SQL> insert into departments_copy select * from departments order by id;
insert into departments_copy select * from departments order by id
*
ERROR at line 1:
ORA-00001: unique constraint (UBU.PK_DP_COPY) violated

结果应如下所示:

SQL> select * from departments_copy;
ID DESCRIPTION
 1 description_copy1
 2 description2
 3 description3
 4 description4
 5 description_copy2
 6 description6
 7 description7
 8 description8
 9 description9
10 description_copy3
11 description11

1 个答案:

答案 0 :(得分:0)

最好在此处使用MERGE声明。我看到你标记了Oracle和SQL Server。以下命令在SQL Server中运行。

MERGE INTO departments_copy DC
USING (select * from departments) D
ON D.ID = DC.ID
WHEN NOT MATCHED THEN
INSERT (DC.ID,DC.DESCRIPTION)
VALUES (D.ID,D.DESCRIPTION)

被修改