您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

转换时Postgres在函数错误/失败时返回空值

转换时Postgres在函数错误/失败时返回空值

这可以通过在plpgsql函数中捕获异常来完成。

create or replace function my_to_timestamp(arg text)
returns timestamP Language plpgsql
as $$
begin
    begin
        return arg::timestamp;
    exception when others then
        return null;
    end;
end $$;

select id, c1, my_to_timestamp(c1) as c2 from a;

假设您定义了一个函数set_null_on_error(anyelement)。呼唤

select set_null_on_error('foo'::timestamp);

执行函数 引发错误

您可以尝试这样的事情:

create or replace function set_null_on_error(kind text, args anyarray)
returns anyelement language plpgsql
as $$
begin
    begin
        if kind = 'timestamp' then
            return args[1]::timestamp;
        elseif kind = 'number' then
            return to_number(args[1], args[2]);
        end if;
    exception when others then 
        return null;
    end;
end; $$;

select set_null_on_error('timestamp', array['2014-01-01']);
select set_null_on_error('number', array['1.22444', '9999D99']);

我认为这样的解决方案太复杂,使用起来非常不方便,并且通常可能会产生难以调试的问题。

Postgres 2022/1/1 18:51:20 有539人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶