Re: Converting between varchar and float when updating - Mailing list pgsql-general

From Alban Hertroys
Subject Re: Converting between varchar and float when updating
Date
Msg-id BF8F71E3-149E-43D5-8CF8-9E55854FC71A@solfertje.student.utwente.nl
Whole thread Raw
In response to Re: Converting between varchar and float when updating  (Thomas Larsen Wessel <mrvelle@gmail.com>)
Responses Re: Converting between varchar and float when updating
List pgsql-general
On 28 Apr 2011, at 15:26, Thomas Larsen Wessel wrote:

> That leads me to two additional questions:
>
> 1) Can I specify how many decimals I want to be stored back from the result? E.g. 2 / 3 = 0.66666666 but I want to
justsave 0.66.  
>
> 2) Can I make a criteria that it should only update on the strings that can be converted. Maybe smth. like:
> UPDATE foo SET bar = (bar::numeric * 2) WHERE bar::is_numeric;
>
>
> Thomas
>
> P.S.: Dmitriy asked why I save these values in VarChar. Well, I agree, that they should be numeric, but I did not
designthe schema which is btw 10 years old.  

Why don't you change that column to a new one with type numeric and offer your application a view that converts it to
varchar?With some rules (see manuals), you could even make that "virtual column" writable. 
It's quite possible that you'll have to rename the table as well, so that the new view can have the name of the current
table.

ALTER TABLE foo RENAME TO realfoo;
ALTER TABLE realfoo ADD COLUMN realbar numeric(6,2);
UPDATE realfoo SET realbar = bar::numeric;
ALTER TABLE realfoo DROP bar;
CREATE VIEW foo AS SELECT foo, realbar::text as bar, baz FROM realbar;
CREATE RULE foo_insert AS ON INSERT TO foo
    DO INSTEAD
    INSERT INTO realfoo (foo, realbar, baz) VALUES (NEW.foo, NEW.bar::numeric, NEW.baz);
CREATE RULE foo_update ...etc.

That way you're calculating and sorting with actual numeric values, but your application still sees a varchar field.

Alban Hertroys

--
Screwing up is an excellent way to attach something to the ceiling.


!DSPAM:737,4db98ac612121628848733!



pgsql-general by date:

Previous
From: Roberto Mello
Date:
Subject: Re: [HACKERS] PostgreSQL Core Team
Next
From: Alban Hertroys
Date:
Subject: Re: GIN index not used