Resetting Primary key without deleting truncating table

浪尽此生 提交于 2019-12-13 12:29:30

问题


I have a table with a primary key, now without any reason I don't know when I am inserting data it is being loaded like this

Pk_Col Some_Other_Col
1           A
2           B
3           C
1002        D
1003        E
1901        F

Is there any way I can reset my table like below, without deleting/ truncating the table?

Pk_Col Some_Other_Col
1           A
2           B
3           C
4           D
5           E
6           F

回答1:


You can't update the IDENTITY column so DELETE/INSERT is the only way. You can reseed the IDENTITY column and recreate the data, like this:

DBCC CHECKIDENT ('dbo.tbl',RESEED,0);    
INSERT INTO dbo.tbl (Some_Other_Col)
SELECT Some_Other_Col
FROM (DELETE FROM tbl OUTPUT deleted.*) d;

That assumes there are no foreign keys referencing this data.




回答2:


If you really, really want to have neat identity values you can write a cursor (slow but maintainable) or investigate any number of "how can I find gaps in my sequence" question on SO and perform an UPDATE accordingly (runs faster but tricky to get right). This becomes exponentially harder when you start having foreign keys pointing back to this table. Be prepared to re-run this script any time data is put into, or removed from this table.

Edit: IDENTITY columns cannot be updated per se. You can, however, SET IDENTITY_INSERT dbo.MyTable ON;, INSERT a row with the desired IDENTITY value and the values from the other columns of an existing row, then DELETE the existing row. The nett effect on the data being the same as an UPDATE.

The only sensible reason to do this is if your table has about two billion rows and you're about to run out of integers for your identity column. If that's the case you have a whole world of other stuff to worry about, too.

But seriously - listen to @Damien, don't worry about it.




回答3:


ALTER TABLE #temp1
DROP CONSTRAINT PK_Id

ALTER TABLE #temp1
DROP COLUMN Id

ALTER TABLE #temp1
ADD  Id int identity(1,1)

Try this one.



来源:https://stackoverflow.com/questions/23133151/resetting-primary-key-without-deleting-truncating-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!