2017-06-17 44 views
1

的類型鑑於這種PL/pgSQL函數如何打印代碼和PostgreSQL/PLPGSQL例外

drop function if exists f(float); 
create function f(x float) 
    returns float 
    language plpgsql 
    as $$ 
    begin 
     return 1/x; 
    exception 
     when others then 
     raise notice 'oops'; 
     return 0::float; 
    end; 
    $$; 

很顯然,select f(0);將導致代碼22012例外,類型division_by_zero。知道這一點,我可以將exception子句的選擇器縮小爲when division_by_zero then ...

但是,對於任意函數,如何獲取錯誤類型?有沒有什麼比如說,raise notice error.code

回答

2

使用sqlstate,例如:

drop function if exists f(float); 
create function f(x float) 
    returns float 
    language plpgsql 
    as $$ 
    begin 
     return 1/x; 
    exception 
     when others then 
     raise notice 'oops %', sqlstate; 
     return 0::float; 
    end; 
$$; 

select f(0); 

NOTICE: oops 22012 
f 
--- 
0 
(1 row) 

瞭解更多關於Errors and MessagesTrapping Errors.