How to alter column to identity(1,1)

本文介绍在SQL Server中如何为已存在的表添加带有标识属性的新列,并提供了两种方法:一是创建新表并保留原有数据;二是直接在现有表上添加新列并删除旧列,但后者无法保留原标识列的数据顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You can't alter the existing columns for identity.

 

You have 2 options,

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

2. Create a new column with identity & drop the existing column

 

But take spl care when these columns have any constraints / relations.

 

 

Code Snippet

/*

            For already craeted table Names

            Drop table Names

            Create table Names

            (

                        ID int,

                        Name varchar(50)

            )

 

            Insert Into Names Values(1,'SQL Server')

            Insert Into Names Values(2,'ASP.NET')

            Insert Into Names Values(4,'C#')

*/

 

 

 

Code Snippet

--In this Approach 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'

 

 

 

Code Snippet

--In this approach 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'

 

 

 

 

 

------------------------------------------------------------------------------------------------

 

 

 

Code Snippet

--create test table

create

table table1 (col1 int, col2 varchar(30))

insert

into table1 values (100, 'olddata')

 

 --add identity column

alter

table table1 add col3 int identity(1,1)

GO

 

--rename or remove old column

exec

sp_rename 'table1.col1', 'oldcol1', 'column'

OR

alter

table table1 drop column col1

--rename new column to old column name

exec

sp_rename 'table1.col3', 'col1', 'column'

GO

 

--add new test record and review table

insert

into table1 values ( 'newdata')

select

* from table1

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值