atoi-like function: is there a better way to do this?

Поиск
Список
Период
Сортировка
От Chris Angelico
Тема atoi-like function: is there a better way to do this?
Дата
Msg-id CAPTjJmprw6m+LdeEc+49cysW=T_cqiGDbuYMULfqyzKBDysK7w@mail.gmail.com
обсуждение исходный текст
Список pgsql-general
One of our tables has a few columns that may be interpreted as strings
or may be numbers (data type is varchar, numbers are stored as
decimal). Generally, operations are performed on the string, but
sometimes we need to parse out a number - without it failing on error.
I wrote the following function to approximate to the semantics of
atoi:

create or replace function str2int(val varchar) returns bigint immutable as $$
begin
    val=substring(val from '[0-9]*');
    if length(val) between 1 and 19 then return val::bigint; end if;
    return 0;
end;
$$ language plpgsql;

It uses a regular expression to chop the string down to just the
leading digits (leading only - '123.45' should parse as 123). Is there
a more efficient way to achieve this?

Thanks!

Chris Angelico

В списке pgsql-general по дате отправления:

Предыдущее
От: Rory Campbell-Lange
Дата:
Сообщение: Re: Return unknown resultset from a function
Следующее
От: Chris Angelico
Дата:
Сообщение: Re: atoi-like function: is there a better way to do this?