我需要将一个表的主键更改为一个标识列,并且在表中已经有许多行。

我有一个脚本来清理id,以确保它们从1开始是顺序的,在我的测试数据库上运行良好。

更改列以具有标识属性的SQL命令是什么?


当前回答

在SQL 2005及以上版本中,有一个技巧可以在不改变表的数据页的情况下解决这个问题。这对于大型表很重要,因为在这些表中,处理每个数据页可能需要花费几分钟或几小时的时间。即使标识列是一个主键,是聚集或非聚集索引的一部分,或者其他可能阻碍更简单的“添加/删除/重命名列”解决方案的陷阱,这个技巧也同样有效。

这里有一个技巧:你可以使用SQL Server的ALTER TABLE…SWITCH语句在不改变数据的情况下更改表的模式,这意味着您可以使用相同的表模式替换IDENTITY表,但没有IDENTITY列。同样的技巧也适用于向现有列添加IDENTITY。

通常,ALTER TABLE…SWITCH用于有效地将分区表中的满分区替换为新的空分区。但它也可以用于非分区表。

我使用这个技巧在不到5秒的时间内将一个25亿行表中的列从IDENTITY转换为非IDENTITY(为了运行一个多小时的查询,其查询计划对非IDENTITY列更有效),然后在不到5秒的时间内恢复IDENTITY设置。

下面是它如何工作的代码示例。

 CREATE TABLE Test
 (
   id int identity(1,1),
   somecolumn varchar(10)
 );
  
 INSERT INTO Test VALUES ('Hello');
 INSERT INTO Test VALUES ('World');
  
 -- copy the table. use same schema, but no identity
 CREATE TABLE Test2
 (
   id int NOT NULL,
   somecolumn varchar(10)
 );
  
 ALTER TABLE Test SWITCH TO Test2;

 -- drop the original (now empty) table
 DROP TABLE Test;

 -- rename new table to old table's name
 EXEC sp_rename 'Test2','Test';
  
 -- update the identity seed
 DBCC CHECKIDENT('Test');

 -- see same records
 SELECT * FROM Test; 

这显然比其他答案更复杂,但如果您的表很大,这可能是一个真正的救星。这里有一些注意事项:

As far as I know, identity is the only thing you can change about your table's columns with this method. Adding/removing columns, changing nullability, etc. isn't allowed. You'll need to drop foriegn keys before you do the switch and restore them after. Same for WITH SCHEMABINDING functions, views, etc. new table's indexes need to match exactly (same columns, same order, etc.) Old and new tables need to be on the same filegroup. Only works on SQL Server 2005 or later I previously believed that this trick only works on the Enterprise or Developer editions of SQL Server (because partitions are only supported in Enterprise and Developer versions), but Mason G. Zhwiti in his comment below says that it also works in SQL Standard Edition too. I assume this means that the restriction to Enterprise or Developer doesn't apply to ALTER TABLE...SWITCH.

TechNet上有一篇很好的文章详细介绍了上述要求。

更新- Eric Wu在下面评论了关于这个解决方案的重要信息。复制在这里,以确保它得到更多的关注:

这里还有一个值得一提的警告。虽然 新表将愉快地从旧表接收数据,并且所有的 新行将按照标识模式插入 从1开始,如果该列是主键,则可能中断。 考虑立即运行DBCC CHECKIDENT('<newTableName>') 切换。详见msdn.microsoft.com/en-us/library/ms176057.aspx 信息。

If the table is actively being extended with new rows (meaning you don't have much if any downtime between adding IDENTITY and adding new rows, then instead of DBCC CHECKIDENT you'll want to manually set the identity seed value in the new table schema to be larger than the largest existing ID in the table, e.g. IDENTITY (2435457, 1). You might be able to include both the ALTER TABLE...SWITCH and the DBCC CHECKIDENT in a transaction (or not-- haven't tested this) but seems like setting the seed value manually will be easier and safer.

显然,如果没有新行被添加到表中(或者它们只是偶尔添加,比如每天的ETL进程),那么这种竞争条件就不会发生,因此DBCC CHECKIDENT是可以的。

其他回答

您不能更改现有列的标识。

你有两个选择,

创建一个带有标识的新表并删除现有表 创建一个具有标识的新列并删除现有列

方法1。(新表)在这里,您可以保留新创建的标识列上的现有数据值。请注意,如果不满足'if not exists',您将丢失所有数据,因此请确保您将条件也放在drop上!

CREATE TABLE dbo.Tmp_Names
    (
      Id int NOT NULL
             IDENTITY(1, 1),
      Name varchar(50) NULL
    )
ON  [PRIMARY]
go

SET IDENTITY_INSERT dbo.Tmp_Names ON
go

IF EXISTS ( SELECT  *
            FROM    dbo.Names ) 
    INSERT  INTO dbo.Tmp_Names ( Id, Name )
            SELECT  Id,
                    Name
            FROM    dbo.Names TABLOCKX
go

SET IDENTITY_INSERT dbo.Tmp_Names OFF
go

DROP TABLE dbo.Names
go

Exec sp_rename 'Tmp_Names', 'Names'

方法2(新列)不能在新创建的标识列上保留现有数据值,标识列将保留数字序列。

Alter Table Names
Add Id_new Int Identity(1, 1)
Go

Alter Table Names Drop Column ID
Go

Exec sp_rename 'Names.Id_new', 'ID', 'Column'

请参阅以下Microsoft SQL Server论坛帖子了解更多细节:

如何将列更改为identity(1,1)

简单的解释

使用sp_RENAME重命名现有列

EXEC sp_RENAME 'Table_Name。Existing_ColumnName', 'New_ColumnName', 'COLUMN'

重命名示例:

现有列UserID被重命名为OldUserID

EXEC sp_RENAME 'AdminUsers.UserID' , 'OldUserID', 'COLUMN'

然后使用alter query添加一个新列来设置为主键和标识值

ALTER TABLE TableName ADD Old_ColumnName INT NOT NULL PRIMARY KEY IDENTITY(1,1)

使用实例设置主键

新创建的列名为UserID

ALTER TABLE Users ADD UserID INT NOT NULL PRIMARY KEY IDENTITY(1,1)

然后删除重命名列

ALTER TABLE Table_Name DROP COLUMN Renamed_ColumnName

删除重命名列的示例

ALTER TABLE Users DROP COLUMN OldUserID

现在,我们向表上的现有列添加了一个主键和标识。

我是一名java开发人员,碰巧加入了一个没有DBA的团队,而作为一名开发人员,我无法获得DBA权限。我的任务是在两个数据库之间移动整个模式,所以没有DBA,我必须通过运行脚本来完成,不能使用SQL Server 2008中的GUI,因为我没有管理权限。

但是,在新模式上运行存储过程时,所有内容都被移动了。表,我发现我丢失了一个表的标识字段。我仔细检查了创建表的脚本,它在那里,但是,SQL Server在我运行脚本时没有得到它。后来,一位DBA告诉我,他以前见过同样的问题。

在任何情况下,对于SQL Server 2008,这些是我采取的步骤来解决这个问题,他们工作,所以我张贴在这里,希望它会对某人有所帮助。这是我所做的,因为我对另一个表有FK依赖,这使得这更困难:

我使用这个查询来验证标识确实缺失,并查看表上的依赖关系。

1)。查找表上的统计信息:

exec sp_help 'dbo.table_name_old';

2)。创建一个重复的、完全相同的新表,只是在原来的PK字段上添加了一个标识字段。

3)。禁用标识以移动数据。

SET IDENTITY_INSERT dbo.table_name ON 

4)。传输数据。

INSERT INTO dbo.table_name_new
(
field1, field2, etc...
)
SELECT 
field1, field2, etc...
FROM 
dbo.table_name_old;

5)。验证数据是否存在。

SELECT * FROM dbo.table_name_new

6)。重新启用标识。

SET IDENTITY_INSERT ToyRecP.ToyAwards.lkpFile_New OFF

7)。这是我找到的获得所有FK关系以验证原始表引用哪个表作为依赖项的最佳脚本 我遇到过很多,所以它是一个保存者!

SELECT f.name AS ForeignKey,
   OBJECT_NAME(f.parent_object_id) AS TableName,
   COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
   OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
   COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
   ON f.OBJECT_ID = fc.constraint_object_id
   ORDER BY ReferenceTableName;

8)。在进行下一步之前,请确保您拥有所有涉及到的表的所有PK和FK脚本。

9)。您可以右键单击每个键并使用SQL Server 2008编写脚本

10)。使用以下语法从依赖表中删除FK:

ALTER TABLE [dbo].[table_name] DROP CONSTRAINT [Name_of_FK]

11)。删除原来的表:

DROP TABLE dbo.table_name_old;

13)。接下来的步骤依赖于您在SQL Server 2008第9步中创建的脚本。

将PK添加到新表中。

——将FK添加到新表中。

——将FK添加回依赖项表。

14)。验证所有内容是否正确和完整。我使用GUI查看表格。

15)。将新表重命名为原始表名。

exec sp_RENAME '[Schema_Name.OldTableName]' , '[NewTableName]';

最后,一切都成功了!

遗憾的是,没有一个;IDENTITY属性属于表而不是列。

更简单的方法是在GUI中完成,但如果没有这个选项,则可以复制数据、删除列、用标识重新添加它,然后放回数据。

请看这里的详细说明。

修改列的标识属性:

In Server Explorer, right-click the table with identity properties you want to modify and click Open Table Definition. The table opens in Table Designer. Clear the Allow nulls check box for the column you want to change. In the Column Properties tab, expand the Identity Specification property. Click the grid cell for the Is Identity child property and choose Yes from the drop-down list. Type a value in the Identity Seed cell. This value will be assigned to the first row in the table. The value 1 will be assigned by default.

就是这样,对我很管用