如何在不删除表数据的情况下在SQL表列中重置身份?
答案 0 :(得分:1)
Marc_s通过重置身份发表评论时,您可能会遇到重复记录的问题
您仍然可以在这里重设身份
例如让我们致电您要重置身份的table A
只需创建一个具有不同名称(如table B
和table A
)的相同表
现在将table A
的数据复制到table B
现在截断或删除table A
中的数据,并重置table A
这是您重置身份而又不会丢失任何数据或没有重复记录的方法
这是实现目标的一种方式 我不确定是否正确
答案 1 :(得分:0)
您可以使用重置命令
DBCC CHECKIDENT ('table_name', RESEED, 1)
语法
('table_name',RESEED,1),其中“ 1”是您的重置点起始编号。新索引将从何处开始。
答案 2 :(得分:0)
尝试以下代码(代码中需要注释):
--smple data preparation
--insert values to have 1 through 5 IDs, delete first three
create table tbl(id int identity(1,1) primary key, [name] char(1));
insert into tbl ([name]) values
('a'),('b'),('c'),('d'),('e');
delete from tbl where id <=3
--create helper table to hold data from our table with updated IDs
create table #helpTmpTbl(id int, [name] char(1));
--updated IDs are obtained with ROW_NUMBER function
insert into #helpTmpTbl
select row_number() over (order by id), [name] from tbl
--here you are exposed to risk of losing data, so we need to use transaction
begin tran
begin try
--delete records from table
delete from tbl
--enable inserting identity column (and always remember to disable it!)
set identity_insert tbl ON
--insert rows with updated IDs
insert into tbl (id, [name])
select * from #helpTmpTbl
--disable inserting identity column
set identity_insert tbl OFF
--if everything is successful, commit transaction
commit tran
end try
begin catch
rollback tran
end catch
select * from tbl
--get rid of the helper table
drop table #helpTmpTb