Problem with Postgres ALTER TABLE

后端 未结 4 1885
死守一世寂寞
死守一世寂寞 2021-02-02 06:47

I have one problem with the ALTER TABLE in postgre. I want to change size of the varchar column. When I try to do this, It says that the view is dependent on that column. I can\

4条回答
  •  一整个雨季
    2021-02-02 07:18

    If you don't need to change the type of the field, but just the size of it, this approach should work:

    Starting with these tables:

    CREATE TABLE foo (id integer primary key, names varchar(10));
    CREATE VIEW voo AS (SELECT id, names FROM foo);
    

    \d foo and \d voo both show the length as 10:

    id     | integer               | not null
    names  | character varying(10) | 
    

    Now change the lengths to 20 in the pg_attribute table:

    UPDATE pg_attribute SET atttypmod = 20+4
    WHERE attrelid IN ('foo'::regclass, 'voo'::regclass)
    AND attname = 'names';
    

    (note: the 20+4 is some crazy postgresql legacy thing, the +4 is compulsory.)

    Now \d foo shows:

    id     | integer               | not null
    names  | character varying(20) | 
    

    Bonus: that was waaay faster than doing:

    ALTER TABLE foo ALTER COLUMN names TYPE varchar(20);
    

    Technically you can change the size of the table column without changing the size of the view column, but no guarantees on what side effects that will have; it's probably best to change them both at once.

    source and fuller explanation: http://sniptools.com/databases/resize-a-column-in-a-postgresql-table-without-changing-data

提交回复
热议问题