sql-server – 在sql server中重新排序Identity主键

前端之家收集整理的这篇文章主要介绍了sql-server – 在sql server中重新排序Identity主键前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是的,我非常清楚后果.但我只是想重新排序它们.从1开始到结束.

如何使用单个查询重新排序密钥?

它是聚簇主键索引

像重新排序一样

First record Id 1 
second record Id 2

主键是Int

解决方法

>丢弃PK约束
>删除标识列
>重新创建标识列
>重新创建PK
USE Test
go

if(object_id('IdentityTest') Is not null)
drop table IdentityTest

create table IdentityTest
(
Id int identity not null,Name varchar(5),constraint pk primary key (Id)
)

set identity_insert dbo.IdentityTest ON
insert into  dbo.IdentityTest (Id,Name) Values(23,'A'),(26,'B'),(34,'C'),(35,'D'),(40,'E')
set identity_insert dbo.IdentityTest OFF



select * from IdentityTest

------------------1. Drop PK constraint ------------------------------------ 
ALTER TABLE [dbo].[IdentityTest] DROP CONSTRAINT [pk]
GO
------------------2. Drop Identity column -----------------------------------
ALTER table dbo.IdentityTest
drop column Id
------------------3. Re-create Identity Column -----------------------------------
ALTER table dbo.IdentityTest
add Id int identity(1,1)
-------------------4. Re-Create PK-----------------------
ALTER TABLE [dbo].[IdentityTest] ADD  CONSTRAINT [pk] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)

--------------------------------------------------------------
insert into  dbo.IdentityTest (Name) Values('F')
select * from IdentityTest
原文链接:https://www.f2er.com/mssql/77327.html

猜你在找的MsSQL相关文章