好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

postgresql 修改列类型操作

习惯了Oracle中:

ALTER TABLE 表名 ALTER COLUMN 列名 新的数据类型[(长度)] NULL或NOT NULL

这种 修改 方式的时候,在pg中:

?

1

2

3

highgo=# create table p1 (id int ,pswd varchar (30), time timestamp );

CREATE TABLE

highgo=# insert into p1 select generate_series(1,500000),md5( 'random()::text' ),clock_timestamp();

错误: 对于可变字符类型来说,值太长了(30)

会发现无法添加成功呢?

highgo=# alter table p1 alter column pswd text NULL;

错误: 语法错误 在 "text" 或附近的

LINE 1: alter table p1 alter column pswd text NULL;

我们来看一下pg中的语法:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

highgo=# \h auto

where action is one of :

 

  ADD [ COLUMN ] [ IF NOT EXISTS ] column_name data_type [ COLLATE collation ] [ column_constraint [ ... ] ]

  DROP [ COLUMN ] [ IF EXISTS ] column_name [ RESTRICT | CASCADE ]

  ALTER [ COLUMN ] column_name [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ]

  ALTER [ COLUMN ] column_name SET DEFAULT expression

highgo=# alter table p1 alter COLUMN pswd type text ;

ALTER TABLE

highgo=# \d p1

        Table "public.p1"

  Column |   Type    | Collation | Nullable | Default

--------+-----------------------------+-----------+----------+---------

  id  | integer       |   |   |

  pswd | text      |   |   |

  time | timestamp without time zone |   |   |

成功!

补充: postgresql 修改字段类型为数组类型(text 改为 text[] )

语法:

alter table tablename alter columnname type oldcolumntype USING columnname:: newcolumntype

eg:

alter table dirty_track alter labels type text USING labels::text[];

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/pg_hgdb/article/details/80769685

查看更多关于postgresql 修改列类型操作的详细内容...

  阅读:53次