我正在尝试将text
值转换为timestamp
值。
对于称为的表a
:
id | c1
----+--------------------
1 | 03-03-2000
2 | 01-01-2000
3 | 12/4/1990
4 | 12 Sept 2011
5 | 12-1-1999 12:33:12
6 | 24-04-89 2:33 am
我正在尝试使用和来执行
select
,如下所示:select id, c1,
c1::timestamp
as c2 from a;
如果只有前5行,则此方法可以正常工作,但是对于
c1
为24-04-89 2:33 am
的第六行,它将引发以下错误:我想要的是
null
,这些值不能将强制转换为时间戳,而不是命令完全失败。像这样: id | c1 | c2
----+--------------------+---------------------
1 | 03-03-2000 | 2000-03-03 00:00:00
2 | 01-01-2000 | 2000-01-01 00:00:00
3 | 12/4/1990 | 1990-12-04 00:00:00
4 | 12 Sept 2011 | 2011-09-12 00:00:00
5 | 12-1-1999 12:33:12 | 1999-12-01 12:33:12
6 | 24-04-89 2:33 am | (null)
(6 rows)
编辑:
另外,有没有通用的方法来实现这一点?即:(基于klin's answer)一个plpgsql包装函数,如果将其包装的函数抛出错误,则将值设置为
null
。例如:可以像这样使用的函数
set_null_on_error
:select id, c1,
set_null_on_error(c1::timestamp)
as c2 from a;
或者
select id, c1,
set_null_on_error(to_number(c1, '99'))
as c2 from a;
最佳答案
这可以通过在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']);
我认为这样的解决方案太复杂,使用起来非常不方便,并且通常可能会产生难以调试的问题。
关于sql - 转换时Postgres在函数错误/失败时返回空值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30800140/