向现有列添加身份 [英] Adding an identity to an existing column

查看:115
本文介绍了向现有列添加身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to change the primary key of a table to an identity column, and there's already a number of rows in table.

我有一个脚本来清理ID,以确保它们从1开始是连续的,在我的测试数据库上可以正常工作。

I've got a script to clean up the IDs to ensure they're sequential starting at 1, works fine on my test database.

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

What's the SQL command to alter the column to have an identity property?

推荐答案

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

You can't alter the existing columns for identity.

您有2个选项,


  1. 使用标识&创建新表删除现有表

  1. Create a new table with identity & drop the existing table

使用标识&创建新列删除现有列

Create a new column with identity & drop the existing column

方法1。(新表)您可以在此处保留

Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.

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(新列)您不能在新创建的标识列上保留现有数据值,标识列将保存numb的序列

Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.

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论坛帖子:

See the following Microsoft SQL Server Forum post for more details:

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

这篇关于向现有列添加身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆