我正在使用sql開發人員,並已添加約束到我的一個表。在psql中捕獲約束違規
constraint valid_gender check(gender in ('M','F','I','T'))
當我嘗試使用plsql過程添加性別爲'x'的條目時,它違反約束(因爲它應該)失敗。
我想添加一個「Catch」到plsql過程,這樣如果valid_gender被聲明,我可以raise_application_error特定於它。這可能嗎?
我正在使用sql開發人員,並已添加約束到我的一個表。在psql中捕獲約束違規
constraint valid_gender check(gender in ('M','F','I','T'))
當我嘗試使用plsql過程添加性別爲'x'的條目時,它違反約束(因爲它應該)失敗。
我想添加一個「Catch」到plsql過程,這樣如果valid_gender被聲明,我可以raise_application_error特定於它。這可能嗎?
甲骨文將提高,上面寫着一個例外:
ORA-02290:檢查約束(yourschema.valid_gender)違反
你能趕上,在異常處理程序,提高自己的異常,而不是通過幾種方式使用raise_application_error
。
1)您可以專門捕獲ORA-02290的例外是這樣的:
declare
e_check_violated exception
pragma exception_init (e_check_violated, -2290);
begin
insert ...
exception
when e_check_violated then
if sqlerrm like '%(yourschema.valid_gender)%' then
raise_application_error(-20001,'Invalid gender');
else
raise;
end if;
end;
2)可以捕獲所有異常,並檢查它們:
begin
insert ...
exception
when others then
if sqlerrm like 'ORA-02290:%(yourschema.valid_gender)%' then
raise_application_error(-20001,'Invalid gender');
else
raise;
end if;
end;
在大型應用還是比較通常有一個異常處理程序來概括這一點,並在表中查找特定於約束的消息。
你可能只是第一個測試:
if gender_value not in ('M','F','I','T') then
raise_application_error...
end if;
使用化名塊在你的代碼...
BEGIN
INSERT or update...
EXCEPTION
WHEN dup_val_on_index THEN
RISE...
END;
三江源非常 – luke
我會+2或+3,如果我能:) –
這是一個比較合適的答案,謝謝 – chulian