如何将 table 数据和结构与标识列及其值复制到同一数据库中的另一个 table(只需更改 table 名称)

How to copy table data and structure with Identity column and its value to another table in the same db(just change table name)

我无法将 table 数据和结构复制到另一个 table,因为我想保留身份列的 Id 列并保留其初始值而不是从 1 开始

我在下面使用 sql 插入除 ID 列之外的所有数据,从 MY_TABLEMY_TABLE_NEW 因为它有错误说

Only when the column list is used and IDENTITY_INSERT is ON, an explicit value can be specified for the identity column in the table'My_TABLE_NEW'.

但是我设置如下SQL:

IF NOT EXISTS (select * from sys.objects where name = 'My_TABLE_NEW')
BEGIN
    CREATE TABLE [dbo].[My_TABLE_NEW]
    (
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [OBJECT_ID] [int] NOT NULL,
        [YEAR_MONTH] [int] NOT NULL,
            
        CONSTRAINT [PK_My_TABLE_NEW] 
            PRIMARY KEY CLUSTERED ([ID] ASC)
                        WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                              IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                              ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
END
GO

IF EXISTS (SELECT * FROM sys.objects WHERE name = 'My_TABLE_NEW')
BEGIN
    SET IDENTITY_INSERT My_TABLE_NEW ON

    INSERT INTO My_TABLE_NEW
        SELECT [ID]
               ,[OBJECT_ID]
              ,[YEAR_MONTH]
        FROM My_TABLE

   SET IDENTITY_INSERT My_TABLE_NEW OFF
END
GO

有什么问题?

来自documentation

When an existing identity column is selected into a new table, the new column inherits the IDENTITY property, unless one of the following conditions is true:

The SELECT statement contains a join, GROUP BY clause, or aggregate function.

Multiple SELECT statements are joined by using UNION.

The identity column is listed more than one time in the select list.

The identity column is part of an expression.

The identity column is from a remote data source.

这意味着您可以用 SELECT INTO 复制 table,同时保留身份列,然后只需添加 PK。

SELECT *
INTO My_TABLE_NEW
FROM My_TABLE

这是 fiddle 的演示。

您可以为此使用内置工具 sp_rename,只要您只是重命名 table 而不是尝试创建它的副本。

EXEC sp_rename 'My_TABLE', 'My_TABLE_NEW'
GO;

https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql?view=sql-server-ver15

如果要创建副本,则只需执行以下操作:

SELECT *
INTO My_TABLE_NEW
FROM My_TABLE

注意:如果这样做,您将不得不重新添加任何键约束、计算值列等。

尝试使用列名插入:

INSERT INTO My_TABLE_NEW ([ID], [OBJECT_ID], [YEAR_MONTH])
        SELECT [ID]
               ,[OBJECT_ID]
              ,[YEAR_MONTH]             
        FROM My_TABLE