我想知道在Oracle中将多个记录复制到一个忽略某个索引上的重复值的数据库中的首选技术。声明在声明中明确说明,而不是来自另一个表
INSERT INTO EXAMPLE (A, B, C, D) VALUES (null,'example1','example2',EXAMPLE_SEQ.nextval);
INSERT INTO EXAMPLE (A, B, C, D) VALUES (null,'example2','example3',EXAMPLE_SEQ.nextval);
INSERT INTO EXAMPLE (A, B, C, D) VALUES (null,'example4','example5',EXAMPLE_SEQ.nextval);
我目前正在这样做,并手动检查,但需要找到一种方法,以便这些可以作为脚本处理
答案 0 :(得分:3)
如果您决定坚持INSERTs
,则可以通过使用约束(无论是主键还是唯一键)来阻止插入重复行。如果它碰巧违反了一个唯一的约束,那么你的脚本就会停止,并且你必须对先前插入所做的所有更改进行roollback(除非你已经提交了每一个)。要处理该异常,您可以编写类似的pls / sql块。
declare
l_unique_exception exception;
pragma exception_init(l_unique_exception, -1);
begin
insert into test(id, test_vector)
values(1, 123);
insert into test(id, test_vector)
values(1, 123);
......
Insert into
commit;
exception
when l_unique_exception
then process the exception;
end;
另外
如果要在其中一个插入引发异常后继续,则以下示例可能会派上用场。
创建一个包含错误的表。例如。
CREATE TABLE tb_errors (
ErrorTag varchar2(123)
)
提供错误记录,调用CREATE_ERROR_LOG包3>的DBMS_ERRLOG程序
DBMS_ERRLOG.CREATE_ERROR_LOG('YourDmlTable. Test in this case', 'tb_errors');
为每个log errors into
insert
子句
醇>
这是一个例子
declare
begin
insert into test(id, col1)
values(1, 123)
log errors into tb_errors('simple expression') reject limit unlimited;
insert into test(id, col1)
values(1, 123)
log errors into tb_errors('simple expression') reject limit unlimited;
insert into test(id, col1)
values(1, 123)
log errors into tb_errors('simple expression') reject limit unlimited;
commit;
end;
脚本完成后,您可以查询错误记录表,在这种情况下为tb_errors
,以查看出现了什么问题。
答案 1 :(得分:2)
您应该查看MERGE
语法。
http://en.wikipedia.org/wiki/Merge_(SQL)
merge example target
using (select 1 as id, 'a' as val) as source
on source.id = target.id
and source.val = target.val
when not matched then
insert (id, val) values (source.id, source.val);
答案 2 :(得分:0)
如果您的目标是提供对错误数据的额外处理,我建议您使用LOG错误子句。请考虑http://www.oracle-base.com/articles/10g/dml-error-logging-10gr2.php - 很好的例子就在那里。