SQL ALTER TABLE(修改表)
SQL ALTER TABLE命令用於添加,刪除或修改列在一個現有的表。
也可以使用ALTER TABLE命令可在現有的表中添加和刪除各種約束。
語法
ALTER TABLE基本語法來添加新的列到現有表如下:
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添加唯一約束到表的基本語法如下:
ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
ALTER TABLE添加CHECK約束到表的基本語法如下:
ALTER TABLE table_name ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
ALTER TABLE添加PRIMARY KEY約束到表的基本語法如下:
ALTER TABLE table_name ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
ALTER TABLE從表中刪除約束的基本語法如下:
ALTER TABLE table_name DROP CONSTRAINT MyUniqueConstraint;
如果使用MySQL,參考代碼如下:
ALTER TABLE table_name DROP INDEX MyUniqueConstraint;
ALTER TABLE從表中刪除主鍵約束的基本語法如下:
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 | +----+----------+-----+-----------+----------+
以下是添加一個新列到現有的表的示例:
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 | +----+---------+-----+-----------+----------+------+
以下是例子,從現有的表中刪除 sex 列:
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 | +----+---------+-----+-----------+----------+