converting varchar to integer

From: tv(at)fuzzy(dot)cz
To: pgsql-sql(at)postgresql(dot)org
Subject: converting varchar to integer
Date: 2005-08-16 23:34:48
Message-ID: 1124235288.43027818cb6e3@email.gigaweb.cz
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hi,

I have a varchar column, and I need to

1) check the value in it is an integer
2) get the integer value (as integer)

The problem is I can't suppose the're only correct
values - ie there can be something like 'xssdkjsd',
'230kdd' or even an empty string etc.

I've been looking through the documentation but I've
found no functions doing this. Are there such functions?

I've been using to_number(...) function, but it raises
an exception on an empty string.

I've written two on my own (see the functions below),
but maybe there's something faster?

Tomas

---------------------------------------------------------------------
-- converts the varchar value to integer
-- the value has to be already checked using the is_integer function
---------------------------------------------------------------------
CREATE OR REPLACE FUNCTION to_integer(VARCHAR) RETURNS INTEGER AS '
DECLARE
str ALIAS FOR $1;
BEGIN
RETURN to_number(str,9999999999);
END;
' LANGUAGE plpgsql;

---------------------------------------------------------------------
-- checks whether the value is an integer (int4)
---------------------------------------------------------------------
CREATE OR REPLACE FUNCTION is_integer(VARCHAR) RETURNS BOOLEAN AS '
DECLARE
str ALIAS FOR $1;
pos INT8 := 0;
BEGIN
-- only 0,1,...,9 (least one)
IF NOT str ~* ''^[0-9]+$'' THEN
RETURN false;
END IF;

SELECT INTO pos to_number($1,9999999999);

-- check the boundaries
IF (-2147483648 <= pos) AND (+2147483647 >= pos) THEN
RETURN true;
ELSE
RETURN false;
END IF;
END;
' LANGUAGE plpgsql;

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Josh Berkus 2005-08-17 00:05:49 Re: converting varchar to integer
Previous Message Bruno Wolff III 2005-08-16 21:05:33 Re: how to do a select * and decrypt a column at the same time?