Re: How to add month.year column validation

From: Scott Marlowe <scott(dot)marlowe(at)gmail(dot)com>
To: Andy Shellam <andy-lists(at)networkmail(dot)eu>
Cc: Andrus <kobruleht2(at)hot(dot)ee>, pgsql-general(at)postgresql(dot)org
Subject: Re: How to add month.year column validation
Date: 2009-12-23 21:43:11
Message-ID: dcc563d10912231343j4819313asbf24bf7b710f2468@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, Dec 23, 2009 at 12:02 PM, Andy Shellam
<andy-lists(at)networkmail(dot)eu> wrote:
> Andrus,
>
>>
>> -- add bad data
>> INSERT INTO foo VALUES ('');
>> INSERT INTO foo VALUES ('02.x');
>> INSERT INTO foo VALUES ('02.1970');
>> INSERT INTO foo VALUES ('02.2101');
>> INSERT INTO foo VALUES (NULL);
>> -- add good data
>> INSERT INTO foo VALUES ('12.2009');
>>
>> delete from foo where tmkuu is null OR NOT ( SUBSTR(tmkuu, 1, 2) IN ('01', '02', '03', '04', '05', '06',
>> '07', '08', '09', '10', '11', '12') AND SUBSTR(tmkuu, 3, 1) = '.' AND
>> SUBSTR(tmkuu, 4, 4)::int BETWEEN 1980 and 2100 );
>>
>> alter table foo alter tmkuu type MonthYear;
>> select * from foo;
>>
>> but got error on DELETE:
>>
>> ERROR:  invalid input syntax for integer: "x"
>>
>> How to apply this constraint to existing data ?
>
>
> Remove the data that doesn't conform to the constraint.
>
> You got the error because you're trying to cast SUBSTR(tmkuu, 4, 4) to an integer in your DELETE statement - but in the case of the second record, that expression cannot be an integer (because of the x) hence the error.

You can use the regex I posted to get rid of the data easily, then go
back to the substr one for a check constraint after that.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Patrick M. Rutkowski 2009-12-23 21:58:47 Re: WARNING: nonstandard use of escape in a string literal
Previous Message Tom Lane 2009-12-23 21:20:58 Re: WARNING: nonstandard use of escape in a string literal