SQL ADD COLUMN
在这篇SQL文章中,您将详细了解ADD COLUMN命令的语法和示例。
ADD COLUMN语句是什么?
在许多SQL情况下,您可能需要在现有表中添加新的列或字段。因此,SQL提供了ALTER TABLE命令中的ADD关键字来解决这个问题。
ALTER TABLE和CREATE TABLE是结构化查询语言中的两个不同的语句,它们允许您添加列。但两个语句之间的区别在于CREATE语句在表创建时添加列,而ALTER语句在现有表中稍后添加一个或多个列。
ADD Column语句的语法
ALTER TABLETable_Name ADD Column_Name Definition_of_New_Column;
此ALTER TABLE语法允许我们向现有表中添加一个新字段。
如果您想在单个SQL查询中向表中添加多个新字段,您必须使用以下语法:
ALTER TABLE table_name
ADD (column_Name_1 column-definition,
column_Name_2 column-definition,
.....,
column_Name_N column-definition);
SQL中ADD列语句的示例
在这里,我们提供了两个不同的结构化查询语言示例,它们将帮助我们在现有表中添加单个和多个字段:
示例1:
首先,我们创建Teacher_Details表,然后向Teacher_Details表插入虚拟记录。
CREATE TABLE Teacher_Details
(
Teacher_ID INT PRIMARY KEY,
First_Name VARCHAR (80),
Course VARCHAR (30) NOT NULL,
Teacher_Address VARCHAR (30),
Teacher_Age INT
) ;
以下的INSERT查询将教师的记录插入到上述表中:
INSERT INTO Teacher_Details (Teacher_ID, First_Name, Course, Teacher_Address, Teacher_Age) VALUES( 2001, Arun, MBA, Goa, 26),
( 1002, Anita, MCA, Ghaziabad, 25),
( 1003, Vishal, MBA, Gorakhpur, 24),
( 1004, Shobhit, BCA, Dehradun, 26),
( 1005, Rohit, MCA, Lucknow, 28),
( 1006, Yogesh, MBA, Jaipur, 28) ;
以下查询显示了Teacher_Details表的记录:
SELECT * FROM Teacher_Details;
Teacher_ID | First_Name | Course | Teacher_Address | Teacher_Age |
---|---|---|---|---|
2001 | Arun | MBA | Goa | 26 |
1002 | Anita | MCA | Ghaziabad | 25 |
1003 | Vishal | MBA | Gorakhpur | 24 |
1004 | shobhit | BCA | Dehradun | 26 |
1005 | Rohit | MCA | Lucknow | 28 |
1006 | Yogesh | MBA | Jaipur | 28 |
下面的查询将新的 Teacher_MailID 列添加到上面的Teacher_Details表中:
ALTER TABLE Cars Teacher_DetailsTeacher_MailID Varchar(100);
示例2:
让我们再举一个例子,该例子在表格中添加了多个列。让我们首先创建另一个Customer表:
CREATE TABLE Customer
(
Cust_Id Int,
First_Name Varchar (20),
Gender Varchar (10),
City Varchar (20),
) ;
下面的查询将多条记录插入到Customer表中:
INSERT INTO Customer (Cust_ID, First_Name, Gender, City) VALUES (501, Jones, Male, Goa),
(502, Arun, Male, Mumbai),
(503, Somya, Female, Shimla),
(504, Ajay, Male, Delhi),
(505, Ram, Male, Dehradun),
(506, Anaya, Female, Haridwar);
Cust_ID | First_Name | Gender | City |
---|---|---|---|
501 | Jones | Male | Goa |
502 | Arun | Male | Mumbai |
503 | Somya | Female | Shimla |
504 | Ajay | Male | Delhi |
505 | Ram | Male | Dehradun |
506 | Anaya | Female | Haridwar |
表格: Customer
以下查询在客户表中添加了两列:
ALTER TABLECustomer ADD ( customer_ContactNo. INT, Customer_EmailID varchar(80);