我有一个表,我要插入1000条记录,我只是使用光标插入。我在插入901记录时出错,它会存储多达900条记录吗?剩下的数据会发生什么。
它不会存储任何东西(至少,不是你放它的方式(。这里有一个例子:
SQL> create table test (id number(1));
Table created.
SQL> begin
2 for i in 1 .. 1000 loop
3 insert into test(id) values (i);
4 end loop;
5 end;
6 /
begin
*
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column
ORA-06512: at line 3
SQL> select * from test;
no rows selected
SQL>
但是,如果您在循环中COMMIT
(这通常是一个坏的想法(,则错误行之前的行将存储到表中:
SQL> begin
2 for i in 1 .. 1000 loop
3 insert into test(id) values (i);
4 commit;
5 end loop;
6 end;
7 /
begin
*
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column
ORA-06512: at line 3
SQL> select * from test;
ID
----------
1
2
3
4
5
6
7
8
9
9 rows selected.
SQL>
[EDIT:如何处理循环中的异常以便继续执行]
正如我在评论中所说,你必须处理这个错误。类似这样的东西:
begin
for cur_e in (select empno, ename from emp) loop
-- inner BEGIN begins here
begin
insert into some_table (col1, col2) values (cur_r.empno, cur_r.ename);
exception
-- if something happens, handle it. I'm using WHEN OTHERS, just as an example
when others then
null; -- don't do anything; silently skip it
end; -- end of the inner block
end loop;
end;
使用这样的代码,您将设法插入所有没有失败的行。所以,如果它在第900行失败,它就会跳过它,继续前进到第901、902、。。。如果它在第950次失败,它将跳过它,进入第951次等