SQLite Alter 命令

sqlite alter 命令

sqlite 的 alter table 命令不通过执行一个完整的转储和数据的重载来修改已有的表。您可以使用 alter table 语句重命名表,使用 alter table 语句还可以在已有的表中添加额外的列。

在 sqlite 中,除了重命名表和在已有的表中添加列,alter table 命令不支持其他操作。

 

1. 语法

用来重命名已有的表的 alter table 的基本语法如下:

alter table database_name.table_name rename to new_table_name;

用来在已有的表中添加一个新的列的 alter table 的基本语法如下:

alter table database_name.table_name add column column_def...;

假设我们的 company 表有如下记录:

id          name        age         address     salary
----------  ----------  ----------  ----------  ----------
1           paul        32          california  20000.0
2           allen       25          texas       15000.0
3           teddy       23          norway      20000.0
4           mark        25          rich-mond   65000.0
5           david       27          texas       85000.0
6           kim         22          south-hall  45000.0
7           james       24          houston     10000.0

现在,让我们尝试使用 alter table 语句重命名该表,如下所示:

sqlite> alter table company rename to old_company;

上面的 sqlite 语句将重命名 company 表为 old_company。现在,让我们尝试在 old_company 表中添加一个新的列,如下所示:

sqlite> alter table old_company add column sex char(1);

现在,company 表已经改变,使用 select 语句输出如下:

id          name        age         address     salary      sex
----------  ----------  ----------  ----------  ----------  ---
1           paul        32          california  20000.0
2           allen       25          texas       15000.0
3           teddy       23          norway      20000.0
4           mark        25          rich-mond   65000.0
5           david       27          texas       85000.0
6           kim         22          south-hall  45000.0
7           james       24          houston     10000.0

请注意,新添加的列是以 null 值来填充的。

下一节:sqlite truncate table

sqlite教程

相关文章