在PostgreSQL中测试函数内的错误

时间:2014-05-15 04:42:49

标签: postgresql

如何检查PostgreSQL功能中的错误?

我的尝试与示例中显示的相同。

示例:

create or replace function fun_testing(sn int, na text, gen text, ad text, rn int, flag int)
returns int as
$$
begin
if flag = 1 then
    insert into testing(ssn,name,gender,address,rno) values(sn,na,gen,ad,rn);

elsif flag = 2 then
    update testing
    set ssn=sn,
    name=na,
    gender=gen,
    address=ad,
    rno = rn
    where ssn=sn;

elsif flag =3 then
    delete from testing
    where ssn =sn;

end if;

if error <> 0 then /* Error Testing */ 
    return(1);
else
    return(0);
end if;
end;
$$
language plpgsql;

错误:列“错误”不存在

注意:相同的if条件(使用@@ error)适用于SQL Server但不能在PostgreSQL中执行。

1 个答案:

答案 0 :(得分:1)

You need a BEGIN ... EXCEPTION ... END block

create or replace function fun_testing(sn int, na text, gen text, ad text, rn int, 
flag int)
returns int as
$$
begin
if flag = 1 then
    insert into testing(ssn,name,gender,address,rno) values(sn,na,gen,ad,rn);

elsif flag = 2 then
    update testing
    set ssn=sn,
    name=na,
    gender=gen,
    address=ad,
    rno = rn
    where ssn=sn;

elsif flag =3 then
    delete from testing
    where ssn =sn;

end if;

exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                 'Transaction was rolled back';

    raise notice '% %', SQLERRM, SQLSTATE;
end;


$$ language 'plpgsql';