Обсуждение: Change attribute type

Поиск
Список
Период
Сортировка

Change attribute type

От
Petter Reinholdtsen
Дата:
How do I change an attributes type, or how do I remove an attribute
from a table.

I have a table created with this command:

  create table test(data int4, changed timestamp);

I want to have this table instead:

  create table test(data int4, changed datetime);

I have lots of entries in the table, and want too keep them when I
change the date type.

The simple method would be to change the type.  Is it possible?

The hard method requires the possibility of removing an attribute.

 1 change name of the attribute
   'alter table test rename column changed to changedold;'
 2 create new attribute
   'alter table test add changed datetime;'
 3 insert old data in new attribute
   'update test set changed = changedold;'
 4 remove the old attribute
   ?

Any clues?

BTW: As I don't follow this mailing-list, could you please send me a
copy when replying?
--
##>  Petter Reinholdtsen <##    | pere@td.org.uit.no
 O-  <SCRIPT Language="Javascript">window.close()</SCRIPT>
http://www.hungry.com/~pere/    | Go Mozilla, go! Go!

Re: [SQL] Change attribute type

От
Herouth Maoz
Дата:
At 18:57 +0300 on 16/7/98, Petter Reinholdtsen wrote:


> I have a table created with this command:
>
>   create table test(data int4, changed timestamp);
>
> I want to have this table instead:
>
>   create table test(data int4, changed datetime);
>
> I have lots of entries in the table, and want too keep them when I
> change the date type.
>
> The simple method would be to change the type.  Is it possible?
>
> The hard method requires the possibility of removing an attribute.
>
>  1 change name of the attribute
>    'alter table test rename column changed to changedold;'
>  2 create new attribute
>    'alter table test add changed datetime;'
>  3 insert old data in new attribute
>    'update test set changed = changedold;'
>  4 remove the old attribute
>    ?
>
> Any clues?

Well, it seems to me the best way is to copy your table into a new one.

1. Rename the table using ALTER TABLE test RENAME to test_temp;

2. Copy the values over to a new table by:

   SELECT data, datetime( changed ) AS changed
   INTO TABLE test
   FROM test_temp;

3. DROP TABLE test_temp;

4. Create indices as needed on the new table.

Alternatively, if your table includes DEFAULT clauses, NOT NULL clauses
etc., your might want to replace step 2 above with the two steps:

2a. CREATE TABLE test ( ... new definition including DEFAULT etc. );

2b. Copy over the values using:

    INSERT INTO test ( data, changed )
    SELECT data, datetime( changed )
    FROM test_temp;

Herouth

--
Herouth Maoz, Internet developer.
Open University of Israel - Telem project
http://telem.openu.ac.il/~herutma