我有两张表deparments
和deparments_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
答案 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)
被修改