如何在sql server 2012中重用主键的自动增量值 [英] how to reuse the autoincrement value of a primary key in sql server 2012

查看:147
本文介绍了如何在sql server 2012中重用主键的自动增量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在sql server 2012中重用主键的自动增量值

how to reuse the autoincrement value of a primary key in sql server 2012

推荐答案

当您删除一些旧记录时,它们的ID不再使用。没有必要通过在这些地方插入新记录来填补删除留下的空白,也不需要重新调整其他记录的ID。

如果你想得到这个数字在表中的现有记录中,使用COUNT:

When you deleted some old records, their IDs are no longer in use. There is no necessity at all to fill in the gaps left by the deletion, neiter by inserting new records into those places nor by re-adjusting the IDs of other records.
If you want to get the number of existing records in a table, use COUNT:
SELECT COUNT(ID) AS [Number of records] FROM MYTABLE



好​​的,有一个添加标识值的技巧:


OK, There is a trick to add identity values:

SET IDENTITY_INSERT MYTABLE ON



其后,你可以将你的ID作为整数值插入。

但是在某些情况下应该谨慎使用:例如:从其他数据库迁移数据时。


Thereafter, you can insert your IDs as integer values.
But that ought to be used carefully, under certain circumstances only: e.g. when migrating data from a different database.


按照我之前的回答 - 自动生成ID .......并删除ID可重复使用..... [ ^ ]。
Follow my previous answer - Auto Generate ID.......And Deleted ID Reusable.....[^].


这篇关于如何在sql server 2012中重用主键的自动增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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