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']);
我认为这样的解决方案太复杂,使用起来非常不方便,并且通常可能会产生难以调试的问题。