服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - PostgreSQL - postgresql 修改列类型操作

postgresql 修改列类型操作

2021-02-21 17:22瀚高PG实验室 PostgreSQL

这篇文章主要介绍了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

延伸 · 阅读

精彩推荐