sql添加列_SQL添加列操作

2023-05-16

sql添加列

This article explains the SQL add column operation into an existing SQL table. We will also explore different examples of SQL add column operations.

本文介绍了对现有SQL表SQL添加列操作。 我们还将探讨SQL添加列操作的不同示例。

Sometimes we want to add columns into an existing table. In existing tables, we might have records in it. We do not want to lose existing data as well. In many circumstances, we can drop the tables and recreate them but this is not recommended generally, especially in a production environment, as it can be destructive as it pertains to data. We can still perform a SQL add column operation using Alter Table command, which avoids have to drop tables, delete data, even if only temporarily.

有时我们想将列添加到现有表中。 在现有表中,我们可能有记录。 我们也不想丢失现有数据。 在许多情况下,我们可以删除表并重新创建它们,但是通常不建议这样做,尤其是在生产环境中,因为它与数据有关可能具有破坏性。 我们仍然可以使用Alter Table命令执行SQL添加列操作,这避免了必须删除表,删除数据(即使只是暂时的)。

句法 (Syntax)

We can perform a SQL add column operation on a table with the following transact SQL command.

我们可以使用以下Transact SQL命令在表上执行SQL添加列操作。

ALTER TABLE table_name
  ADD column_name column_definition;

准备环境 (Prepare the environment)

We need to select a Database table and insert data into it.

我们需要选择一个数据库表并将数据插入其中。

Execute the following query to create an Employee table in SQLShackDemo database.

执行以下查询以在SQLShackDemo数据库中创建Employee表。

USE [SQLShackDemo]
GO
 
SET ANSI_NULLS ON
GO
 
SET QUOTED_IDENTIFIER ON
GO
 
CREATE TABLE [dbo].[Employee](
  [EmpID] [int] IDENTITY(1,1) NOT NULL,
  [EmpName] [varchar](50) NULL,
  [City] [varchar](30) NULL,
  [Designation] [varchar](30) NULL,
PRIMARY KEY CLUSTERED 
(
  [EmpID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Execute the following query to insert sample data into it.

执行以下查询以将示例数据插入其中。

USE [SQLShackDemo];
GO
INSERT INTO [dbo].[Employee]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(1, 
 N'Charlotte Robinson', 
 N'Chicago', 
 N'Consultant'
);
GO
INSERT INTO [dbo].[Employee]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(2, 
 N'Madison Phillips', 
 N'Dallas', 
 N'Senior Analyst'
);
GO
INSERT INTO [dbo].[Employee]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(3, 
 N'Emma Hernandez', 
 N'Phoenix', 
 N'Senior Analyst'
);
GO
INSERT INTO [dbo].[Employee]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(4, 
 N'Samantha Sanchez', 
 N'San Diego', 
 N'Principal Conultant'
);
GO
INSERT INTO [dbo].[Employee]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(5, 
 N'Sadie Ward', 
 N'San Antonio', 
 N'Consultant'
);
GO
INSERT INTO [dbo].[Employee]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(6, 
 N'Savannah Perez', 
 N'New York', 
 N'Principal Conultant'
);
GO
INSERT INTO [dbo].[Employee]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(7, 
 N'Victoria Gray', 
 N'Los Angeles', 
 N'Assistant'
);
GO
INSERT INTO [dbo].[Employee]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(8, 
 N'Alyssa Lewis', 
 N'Houston', 
 N'Consultant'
);
GO
INSERT INTO [dbo].[Employee]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(9, 
 N'Anna Lee', 
 N'San Jose', 
 N'Principal Conultant'
);
GO
INSERT INTO [dbo].[Employee]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(10, 
 N'Riley Hall', 
 N'Philadelphia', 
 N'Senior Analyst'
);
GO
SET IDENTITY_INSERT [dbo].[Employee] OFF;
GO
 

In the following screenshot, we can see the existing data in the Employee table.

在以下屏幕截图中,我们可以在Employee表中看到现有数据。

在现有SQL表上执行SQL添加列操作 (SQL add column operation on an existing SQL table)

We want to add the column department in the Employee table. Suppose we have many columns in a table; we need to check if a particular column exists in the SQL table or not. If the specified column does not exist, we want to create it with the appropriate data type.

我们要在Employee表中添加列部门 。 假设一个表中有很多列; 我们需要检查SQL表中是否存在特定的列。 如果指定的列不存在,我们想使用适当的数据类型创建它。

We can use the INFORMATION_SCHEMA view to check tables and their columns within a database. Execute the following code to get a list of columns, their data type in Employee table.

我们可以使用INFORMATION_SCHEMA视图来检查数据库中的表及其列。 执行以下代码以获取列列表,列的类型在Employee表中。

SELECT TABLE_CATALOG, 
       TABLE_SCHEMA, 
       TABLE_NAME, 
       COLUMN_NAME, 
       DATA_TYPE, 
       IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Employee';

In this output, we can see the Employee table contains 4 columns.

在此输出中,我们可以看到Employee表包含4列。

Let’s add a new column Department with following Alter Table command.

让我们使用下面的Alter Table命令添加一个新的部门Department。

ALTER TABLE Employee
    ADD Department  Varchar(50)

Execute this query and select records from the Employee table. In the following screenshot, we can look at the new column Department. All existing records contain a NULL value in this column.

执行此查询,然后从Employee表中选择记录。 在下面的屏幕截图中,我们可以查看新列Department。 全部存在 记录在此列中包含NULL值。

Previously, we checked all columns in the Employee table using INFORMATION_SCHEMA view. In the following query, we want to create a Department table only if it does not exist in the Employee table.

以前,我们使用INFORMATION_SCHEMA视图检查Employee表中的所有列。 在下面的查询中,我们只想创建一个Department表(如果它在Employee表中不存在)。

IF NOT EXISTS
(
    SELECT *
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'Employee'
          AND COLUMN_NAME = 'Department'
)
    BEGIN
        ALTER TABLE Employee
        ADD Department VARCHAR(50);
END;

We can add a column in an existing table if it allows NULL values or have a default value defined on it. We can try to add Not NULL column in the existing SQL table, but it gives the following error message,

如果它允许NULL值或在其上定义了默认值,则可以在现有表中添加一列。 我们可以尝试在现有SQL表中添加Not NULL列,但是会显示以下错误消息,

IF NOT EXISTS
(
    SELECT *
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'Employee'
          AND COLUMN_NAME = 'Phone'
)
    BEGIN
        ALTER TABLE Employee
        ADD Phone VARCHAR(15) Not NULL;
END;

SQL将列操作添加到具有默认值的现有SQL表中 (SQL add column operation to an existing SQL table with a default value )

Suppose we want to add the column IsActive column into the Employee table. We can have the following values in this column

假设我们要将列IsActive列添加到Employee表中。 我们可以在此列中具有以下值

  • Value 1: Employee is active 值1:员工活跃
  • Value 0: Employee is not active 值0 :员工未处于活动状态

By default, all existing and new employee should have Value 1 in IsActive column. We can specify a value using default constraint.

默认情况下,所有现有员工和新员工的IsActive列均应具有值1 。 我们可以使用默认约束来指定一个值。

If we try to add a column with a Not NULL value in the existing SQL table, we get following error message,

如果我们尝试在现有SQL表中添加具有非NULL值的列,则会收到以下错误消息,

IF NOT EXISTS
(
    SELECT *
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'Employee'
          AND COLUMN_NAME = 'Phone'
)
    BEGIN
        ALTER TABLE Employee
        ADD IsActive bit DEFAULT(1);
END;

Execute this query and Select records from a table. For existing records, it does not update the default values.

执行此查询,然后从表中选择记录。 对于现有记录,它不会更新默认值。

If we insert any new record in this table, it gets default value as per the following screenshot.

如果我们在此表中插入任何新记录,则它将按照以下屏幕截图获取默认值。

SQL向具有标识列的现有SQL表添加列操作 (SQL add column operation to an existing SQL table with an identity column )

In SQL Server, we use the Identity function to define a default and auto increment value for each new row. We can add an identity column to the existing SQL table as well. Let’s create a new table Employee_new without an identity column.

在SQL Server中,我们使用Identity函数为每个新行定义默认值和自动增量值。 我们也可以在现有SQL表中添加一个标识列。 让我们创建一个没有标识列的新表Employee_new

CREATE TABLE [dbo].[Employee_new](
  [EmpID] [int]  NOT NULL,
  [EmpName] [varchar](50) NULL,
  [City] [varchar](30) NULL,
  [Designation] [varchar](30) NULL
)

Once the table is there, we can add an identity column with the following query.

表格到位后,我们可以使用以下查询添加一个身份列。

IF NOT EXISTS
(
    SELECT *
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'Employee_new'
          AND COLUMN_NAME = 'ID'
)
    BEGIN
        ALTER TABLE Employee_new
                 ADD ID INT IDENTITY(1,1) NOT NULL
END;

We created the Identity column in a table without any record in it. Let’s drop the table and recreate it. Insert a few records with the following query.

我们在表中创建了Identity列,但其中没有任何记录。 让我们删除表并重新创建它。 使用以下查询插入一些记录。

INSERT INTO [dbo].[Employee_new]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(8, 
 N'Alyssa Lewis', 
 N'Houston', 
 N'Consultant'
);
GO
INSERT INTO [dbo].[Employee_new]
([EmpID], 
 [EmpName], 
 [City], 
 [Designation]
)
VALUES
(9, 
 N'Anna Lee', 
 N'San Jose', 
 N'Principal Conultant'
);

We have data in the Employee_new table. Let’s add an Identity column with Alter table command.

我们在Employee_new表中有数据。 让我们用Alter table命令添加一个Identity列。

IF NOT EXISTS
(
    SELECT *
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'Employee_new'
          AND COLUMN_NAME = 'ID'
)
    BEGIN
        ALTER TABLE Employee_new
         ADD ID INT IDENTITY(1,1) NOT NULL
END;

In the following screenshot, we can see it updates existing records as well.

在以下屏幕截图中,我们可以看到它也更新了现有记录。

具有标识列的现有SQL表的多个SQL添加列操作 (Multiple SQL add column operations for an existing SQL table with an identity column)

We might need to add multiple columns to an existing SQL table. We can do it within the same Alter table command.

我们可能需要将多个列添加到现有SQL表中。 我们可以在同一Alter table命令中完成此操作。

In the following query, we added two columns ZipCode and StateCode in a single Alter Table command. We need to specify all columns to add in a similar format.

在以下查询中,我们在一个Alter Table命令中添加了两列ZipCode和StateCode。 我们需要指定所有列以类似的格式添加。

ALTER TABLE Employee_new
ADD ZipCode   INT NULL, 
    StateCode INT NULL;
GO

We can get details of all columns and their properties using sp_help command.

我们可以使用sp_help命令获取所有列及其属性的详细信息。

sp_help 'Employee_new'

SQL使用SSMS中的表设计器将列操作添加到现有SQL表中 (SQL add column operation to an existing SQL table with the table designer in SSMS)

In previous examples, we used t-SQL to add columns in the existing table. We might not be familiar with writing t-SQL code. We can use the SSMS GUI as well to add a column.

在前面的示例中,我们使用t-SQL在现有表中添加列。 我们可能不熟悉编写t-SQL代码。 我们也可以使用SSMS GUI添加列。

Right click on the table and click on Design.

右键单击表格,然后单击“ 设计”

It opens a table designer. We can see all existing column, their data types, default values and other properties for a specified table in a table designer

打开表设计器。 我们可以在表设计器中查看指定表的所有现有列,它们的数据类型,默认值和其他属性

Provide a column name and select data types from the drop-down. We can add multiple columns in this with appropriate data types.

提供列名,然后从下拉列表中选择数据类型。 我们可以在其中添加具有适当数据类型的多个列。

Once done, Save and exit the table designer in SSMS. If you try to close it without saving changes, we get a warning message as well.

完成后, 保存并退出SSMS中的表设计器。 如果您尝试在不保存更改的情况下关闭它,我们也会收到一条警告消息。

Click on Yes to save new column in the existing table. We can either run a Select statement to verify the new column or use sp_help command to list all columns and their properties.

单击将新列保存在现有表中。 我们可以运行Select语句以验证新列,也可以使用sp_help命令列出所有列及其属性。

sp_help 'Employee.'

In the following screenshot, we can see a new column in the Employee table.

在以下屏幕截图中,我们可以在Employee表中看到一个新列。

结论 (Conclusion)

In this article, we explored SQL add column operations to add a a new column to an existing SQL table. We can use both the GUI and transact SQL method to do it. I hope you found this article helpful. You can provide feedback or comments in the comments section below.

在本文中,我们探讨了SQL添加列操作,以向现有SQL表添加新列。 我们可以同时使用GUI和事务SQL方法。 希望本文对您有所帮助。 您可以在下面的评论部分中提供反馈或评论。

翻译自: https://www.sqlshack.com/sql-add-column-operations/

sql添加列

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

sql添加列_SQL添加列操作 的相关文章

随机推荐