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添加列操作 的相关文章

  • 在 Mysql 上使用 EntityManager JPA 运行脚本

    我正在尝试运行脚本 sql 文件 但由于我尝试了多种方法 因此出现多个错误 这是我的主要 sql 脚本 INSERT INTO Unity VALUES 11 paq 0 2013 04 15 11 41 37 Admin Paquete
  • Spring Data JPA 选择不同

    我有一个情况 我需要建立一个select distinct a address from Person a 其中地址是 Person 内的地址实体 类型的查询 我正在使用规范动态构建我的 where 子句并使用findAll Specifi
  • 如何连续添加起始行和下一行的值

    我只想创建一个 sql 查询 结果就像图片上的那样 类似于 SQL 中的斐波那契数列 Ex Column 1 10 则 Result 列的值为 Result 10 因为这是第一行 然后假设column1第二行的值为50 那么Result第二
  • 自动删除主键序列中的间隙

    我正在创建一个网页 该网页根据用户操作将数据存储到 MySQL 数据库中 数据库有很多行 行的主键是列 rowID 它只是按顺序对行进行编号 例如 1 2 3 4 用户可以选择删除行 问题是当用户删除最后一行以外的行时 rowID 中有一个
  • java库维护数据库结构

    我的应用程序一直在开发 所以偶尔 当版本升级时 需要创建 更改 删除一些表 修改一些数据等 通常需要执行一些sql代码 是否有一个 Java 库可用于使我的数据库结构保持最新 通过分析类似 db structure version 信息并执
  • 标量子查询包含多行

    我正在使用 H2 数据库并想要移动一些数据 为此 我创建了以下查询 UPDATE CUSTOMER SET EMAIL SELECT service EMAIL FROM CUSTOMER SERVICE AS service INNER
  • SQL Server 2008 错误 233

    我正在使用以下 sql 脚本在 SQL Server 2008 中创建新登录名 CREATE LOGIN xyz WITH PASSWORD xyz DEFAULT DATABASE master DEFAULT LANGUAGE us e
  • 没有为 1 个或多个必需参数给出值。更新SQL

    我正在编写一个程序 当用户在列表视图上选择记录时 该程序会更新密码或积分 我收到错误 没有为 1 个或多个必需参数给出值 我不知道如何纠正 我是否遗漏了一些明显的东西 Dim sql As String UPDATE Users SET P
  • 将两个表合并为一个输出

    假设我有两张表 已知营业时间 ChargeNum CategoryID Month Hours 111111 1 2 1 09 10 111111 1 3 1 09 30 111111 1 4 1 09 50 222222 1 3 1 09
  • 3 个表的 SQL 查询(或联接)

    第一次在 Stack Overflow 上问问题 很棒的资源 但是只有一件事真正让我作为 SQL 新手感到困惑 我有三个表 我想获取与鲍勃的学生相关的所有导师的姓名 表 1 教师 ID Name 1 Bob 表 2 学生 STUDENT I
  • 获取在任何日期创建的表的列表?

    我遇到了这样的情况 我想查找我在 2012 年 9 月 14 日 2012 年 9 月 14 日 在 sql server 上创建的表 是否有任何查询会列出在此日期创建的这些表 SELECT FROM sys tables WHERE cr
  • Java、Oracle 中索引处缺少 IN 或 OUT 参数:: 1 错误

    您好 我使用 Netbeans 8 0 2 和 Oracle 11g Express Edition 在 JSF 2 2 中编写了一个图书馆管理系统 我有几个名为 书籍 借阅者 等的页面 以及数据库中一些名为相同名称的表 我的问题是这样的
  • Oracle SQL 函数中可以有 commit 语句吗

    在 SQL 函数中使用 COMMIT 语句是否可能 有意义 从技术上来说 答案是肯定的 你can请执行下列操作 create or replace function committest return number as begin upd
  • IIF(...) 不是公认的内置函数

    我正在尝试在 Microsoft SQL Server 2008 R2 中使用它 SET SomeVar SomeOtherVar IIF SomeBool value when true value when false 但我收到一个错误
  • 如何使用原始 SQL 查询实现搜索功能

    我正在创建一个由 CS50 的网络系列指导的应用程序 这要求我仅使用原始 SQL 查询而不是 ORM 我正在尝试创建一个搜索功能 用户可以在其中查找存储在数据库中的书籍列表 我希望他们能够查询 书籍 表中的 ISBN 标题 作者列 目前 它
  • ORA-12728: 正则表达式中的范围无效

    我想检查表中是否插入了有效的电话号码 所以我的触发代码在这里 select start index into mob index from gmarg mobile operators where START INDEX substr ne
  • SQL Server使用in关键字传递字符串数组查询

    我认为 IN 子句不能接受具有多个值的绑定参数 Oracle 不能 需要几分钟 查询是 declare setting varchar max set setting Sales Entry Grid Cursor Customer Man
  • 处理与不同相关实体的一对多的正确模式

    我有一个 C 项目 我使用实体框架作为 ORM 我有一个User 可以向多家银行付款 每家银行都是一个独立的实体 并且每家银行都由不同的字段描述 问题是 一User可以没有或有很多不同的Banks 我不太确定如何对此进行建模 临时解决方案是
  • 具有不同组合的产品和产品包的数据库模型

    您将如何设计数据库来实现此功能 考虑一个场景 我们想要创建一个产品关系 封装 假设我们创建一个产品表 prod id prod name prod fee 1 prepaid A 19 usd 2 prepaid B 29 usd 3 pr
  • 查看Jasper报告执行的SQL

    运行 Jasper 报表 其中 SQL 嵌入到报表文件 jrxml 中 时 是否可以看到执行的 SQL 理想情况下 我还想查看替换每个 P 占位符的值 Cheers Don JasperReports 使用 Jakarta Commons

随机推荐