sql - Ignore results that generate an error -
i'm trying make following request
select login, time table time::timestamp <= (current_timestamp - interval '5' month);
where time text field containing timestamps.
is there way can ignore ignore rows generate cast error when time not formatted ?
i've tried following
select login, time table (((current_timestamp - interval '6' month)::text || time)::timestamp <= (current_timestamp - interval '5' month);
but first, in not beautiful , second, results in error: time zone displacement out of range
error, don't understand.
you can write own cast function in plpgsql error handling.
create or replace function to_timestamp_ignore_errors(text) returns timestamp $$ begin return $1::timestamp; exception when others return null; end; $$ language plpgsql immutable strict; postgres=# select to_timestamp_ignore_errors('bbbb'); to_timestamp_ignore_errors ---------------------------- (1 row) postgres=# select to_timestamp_ignore_errors('2013-08-16'); to_timestamp_ignore_errors ---------------------------- 2013-08-16 00:00:00 (1 row)
other possibility format check before casting - initial version
create or replace function to_timestamp_ignore_errors(text) returns timestamp $$ -- regular should richer select case when $1 ~ '^\d{4}-\d{2}-\d{2}$' $1::timestamp else null end; $$ language sql; create function postgres=# select to_timestamp_ignore_errors('2013-08-16'); to_timestamp_ignore_errors ---------------------------- 2013-08-16 00:00:00 (1 row) postgres=# select to_timestamp_ignore_errors('bbbb'); to_timestamp_ignore_errors ---------------------------- (1 row)
tested on 9.2
regular expression based version should little bit faster (30%) when there minimum errors, , faster when lot of errors, solution preferable. so, preferable solution cleaning data , using types.
Comments
Post a Comment