X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 5BE05529E6 for ; Tue, 16 Aug 2005 20:34:50 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 38883-06 for ; Tue, 16 Aug 2005 23:34:49 +0000 (GMT) Received: from zeus.gigaweb.cz (zeus.gigaweb.cz [81.0.236.19]) by svr1.postgresql.org (Postfix) with SMTP id 22D51528A6 for ; Tue, 16 Aug 2005 20:34:46 -0300 (ADT) Received: (qmail 29949 invoked from network); 16 Aug 2005 23:34:48 -0000 Received: from unknown (HELO localhost) (81.0.236.19) by 0 with SMTP; 16 Aug 2005 23:34:48 -0000 Received: from pha-84-242-95-3.nat.karneval.cz (pha-84-242-95-3.nat.karneval.cz [84.242.95.3]) by email.gigaweb.cz (IMP) with HTTP for ; Wed, 17 Aug 2005 01:34:48 +0200 Message-ID: <1124235288.43027818cb6e3@email.gigaweb.cz> Date: Wed, 17 Aug 2005 01:34:48 +0200 From: tv@fuzzy.cz To: pgsql-sql@postgresql.org Subject: converting varchar to integer MIME-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit User-Agent: Internet Messaging Program (IMP) 3.2.3 X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=-0.527 required=5 tests=[AWL=-0.705, NO_REAL_NAME=0.178] X-Spam-Level: X-Archive-Number: 200508/118 X-Sequence-Number: 22346 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;