如果你想在 ORA 代码的情况下回滚/做一些额外的事情,那么在 SQL*PLUS 会话中做这一切。
即作为脚本运行它。
set serverout on
begin
update...;
exception
when others -- others is a catch all, you can catch specific codes too
then
rollback;
dbms_output.put_line('Error!');
dbms_output.put_line(sqlerrm); -- prints full error string
end;
/
如果您只是想向 bash 发出一条 sql 语句失败的信号,您可以在 sql*plus 中设置为第一件事。whenever sqlerror exit sql.sqlcode
(或whenever sqlerror (exit -1
等)代替(见这里)。这将在第一个错误时停止,并使用适当的返回代码返回您的 schell 脚本。
您可以嵌套块,例如:
begin
update ..;
begin
select id into v_id
from tab
where ...;
exception
when no_data_found
then
null;-- ignore that we didnt find a row
end;
-- if the select fails, we continue from here..
delete...;
begin
savepoint mysave;
your_proc(...);
exception
when others
then
rollback to mysave; -- of the call to your_proc fails, lets just toll that back alone
end;
end;
等等
如果您需要它是交互式的,您可以执行类似 (dbms_alert)[http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_alert.htm#CHDCFHCI] 的操作:
sqlplus /<<EOF | tee -a my.log
set feedback on verify on serverout on
-- IE YOUR CODE HERE..
select * from dual;
begin
null;
end;
/
-- END OF YOUR CODE..
-- now lets wait for an alert from another session:
declare
v_message varchar2(32767);
v_status number;
begin
DBMS_ALERT.REGISTER('should_i_commit');
DBMS_ALERT.WAITONE('should_i_commit', v_message, v_status); -- there is a timeout parameter you can set too
if (v_message = 'Y')
then
dbms_output.put_line('I committed');
commit;
else
dbms_output.put_line('I rolled back');
rollback;
end if;
end;
/
EOF
然后在另一个会话中,您可以发出:
SQL> exec dbms_alert.signal('should_i_commit', 'N');
PL/SQL procedure successfully completed.
SQL> commit;
Commit complete.