Re: Casting from varchar to numeric

From: "Joel Burton" <joel(at)joelburton(dot)com>
To: <tansley(at)law(dot)du(dot)edu>, <pgsql-novice(at)postgresql(dot)org>
Subject: Re: Casting from varchar to numeric
Date: 2002-05-16 17:47:39
Message-ID: JGEPJNMCKODMDHGOBKDNCEHGCOAA.joel@joelburton.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

> -----Original Message-----
> From: pgsql-novice-owner(at)postgresql(dot)org
> [mailto:pgsql-novice-owner(at)postgresql(dot)org]On Behalf Of Tom Ansley
> Sent: Thursday, May 16, 2002 11:49 AM
> To: pgsql-novice(at)postgresql(dot)org
> Subject: [NOVICE] Casting from varchar to numeric
>
> Is there a way of casting from a varchar to a numeric type?
>
> My problem consists of a varchar(10) that are all numeric. They
> are telephone
> numbers and I want to convert them during a select statement to (XXX)
> XXX-XXXX

Casting from VARCHAR to NUMERIC? Sounds like you want to go from a VARCHAR
containing only digits to a formatted VARCHAR, right? From "2025551212" ->
"(202) 555-1212"

CREATE TABLE Phones (p VARCHAR(10));

INSERT INTO Phones VALUES ('2025551212');

SELECT '(' || SUBSTRING(p FROM 1 FOR 3) || ') ' ||
SUBSTRING(p FROM 4 FOR 3) || '-' || SUBSTRING(p FROM 7) FROM Phones;

Tho I would make a plpgsql function for the phone display, making it easier
to re-use:

CREATE OR REPLACE FUNCTION to_phone(VARCHAR) RETURNS VARCHAR AS '
DECLARE
p ALIAS FOR $1;
BEGIN
RETURN ''('' || SUBSTRING(p FROM 1 FOR 3) || '') '' ||
SUBSTRING(p FROM 4 FOR 3) || ''-'' || SUBSTRING(p FROM 7);
END;'
LANGUAGE plpgsql WITH (isCachable);

This way you can simply say SELECT to_phone(p) FROM Phones, plus you can
create an index on to_phone(p), so that, if you want to see phones formatted
this way often, it'll be much quicker.

- J.

Joel BURTON | joel(at)joelburton(dot)com | joelburton.com | aim: wjoelburton
Knowledge Management & Technology Consultant

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Joel Burton 2002-05-16 20:36:43 Re: newbie: Column CHECK(col contains '@') ?
Previous Message Tom Ansley 2002-05-16 17:18:33 Re: Casting from varchar to numeric