ALTER TABLE ADD 和 DROP COLUMN 示例 - Amazon Redshift
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

ALTER TABLE ADD 和 DROP COLUMN 示例

以下示例演示如何使用 ALTER TABLE 添加基本表列,然后删除该列;另外还演示如何删除具有从属对象的列。

添加基本列,然后删除该列

以下示例将独立 FEEDBACK_SCORE 列添加到 USERS 表。该列只包含一个整数,并且该列的默认值为 NULL(无反馈分数)。

首先,查询 PG_TABLE_DEF 目录表以查看 USERS 表的架构:

column | type | encoding | distkey | sortkey --------------+------------------------+----------+---------+-------- userid | integer | delta | true | 1 username | character(8) | lzo | false | 0 firstname | character varying(30) | text32k | false | 0 lastname | character varying(30) | text32k | false | 0 city | character varying(30) | text32k | false | 0 state | character(2) | bytedict | false | 0 email | character varying(100) | lzo | false | 0 phone | character(14) | lzo | false | 0 likesports | boolean | none | false | 0 liketheatre | boolean | none | false | 0 likeconcerts | boolean | none | false | 0 likejazz | boolean | none | false | 0 likeclassical | boolean | none | false | 0 likeopera | boolean | none | false | 0 likerock | boolean | none | false | 0 likevegas | boolean | none | false | 0 likebroadway | boolean | none | false | 0 likemusicals | boolean | none | false | 0

现在添加 feedback_score 列:

alter table users add column feedback_score int default NULL;

从 USERS 中选择 FEEDBACK_SCORE 列以验证该列已添加:

select feedback_score from users limit 5; feedback_score ---------------- NULL NULL NULL NULL NULL

删除该列以恢复原始 DDL:

alter table users drop column feedback_score;

删除具有从属对象的列

以下示例删除具有从属对象的列。结果是,同时删除从属对象。

开始时,将 FEEDBACK_SCORE 列重新添加到 USERS 表:

alter table users add column feedback_score int default NULL;

接下来,从名为 USERS_VIEW 的 USERS 表创建一个视图:

create view users_view as select * from users;

现在,尝试从 USERS 表中删除 FEEDBACK_SCORE 列。此 DROP 语句使用默认行为 (RESTRICT):

alter table users drop column feedback_score;

Amazon Redshift 显示一条错误消息,说明由于另一个对象依赖该列而无法删除该列。

重新尝试删除 FEEDBACK_SCORE 列,这次指定 CASCADE 以删除所有从属对象:

alter table users drop column feedback_score cascade;