SQL - ALTER TABLE 命令
-
简述
SQLALTER TABLE命令用于添加、删除或修改现有表中的列。您还应该使用 ALTER TABLE 命令在现有表上添加和删除各种约束。 -
句法
添加一个 ALTER TABLE 命令的基本语法New Column在现有表中如下。ALTER TABLE table_name ADD column_name datatype;
ALTER TABLE 命令的基本语法DROP COLUMN在现有表中如下。ALTER TABLE table_name DROP COLUMN column_name;
用于更改表的 ALTER TABLE 命令的基本语法DATA TYPE表中的一列如下。ALTER TABLE table_name MODIFY COLUMN column_name datatype;
添加一个 ALTER TABLE 命令的基本语法NOT NULL对表中列的约束如下。ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
ALTER TABLE 的基本语法ADD UNIQUE CONSTRAINT表如下。ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
ALTER TABLE 命令的基本语法ADD CHECK CONSTRAINT表如下。ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
ALTER TABLE 命令的基本语法ADD PRIMARY KEY对表的约束如下。ALTER TABLE table_name ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
ALTER TABLE 命令的基本语法DROP CONSTRAINT从表如下。ALTER TABLE table_name DROP CONSTRAINT MyUniqueConstraint;
如果你使用 MySQL,代码如下:ALTER TABLE table_name DROP INDEX MyUniqueConstraint;
ALTER TABLE 命令的基本语法DROP PRIMARY KEY表中的约束如下。ALTER TABLE table_name DROP CONSTRAINT MyPrimaryKey;
如果你使用 MySQL,代码如下:ALTER TABLE table_name DROP PRIMARY KEY;
-
例子
考虑具有以下记录的 CUSTOMERS 表 -+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+
以下是添加的示例New Column到现有表 -ALTER TABLE CUSTOMERS ADD SEX char(1);
现在,CUSTOMERS 表已更改,SELECT 语句将输出以下内容。+----+---------+-----+-----------+----------+------+ | ID | NAME | AGE | ADDRESS | SALARY | SEX | +----+---------+-----+-----------+----------+------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | NULL | | 2 | Ramesh | 25 | Delhi | 1500.00 | NULL | | 3 | kaushik | 23 | Kota | 2000.00 | NULL | | 4 | kaushik | 25 | Mumbai | 6500.00 | NULL | | 5 | Hardik | 27 | Bhopal | 8500.00 | NULL | | 6 | Komal | 22 | MP | 4500.00 | NULL | | 7 | Muffy | 24 | Indore | 10000.00 | NULL | +----+---------+-----+-----------+----------+------+
以下是从现有表中删除性别列的示例。ALTER TABLE CUSTOMERS DROP SEX;
现在,CUSTOMERS 表已更改,以下将是 SELECT 语句的输出。+----+---------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+---------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Ramesh | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | kaushik | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+---------+-----+-----------+----------+