主键自动分配,可用数量最少 [英] Primary-Key Auto assign with minimum available number

查看:84
本文介绍了主键自动分配,可用数量最少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表值如下.

Id(pk)项目
1台笔记本电脑
2 Pendrive
5鼠标
=====================
当我在表格中插入新项目时,它应该分配3号作为ID(即可用的最小编号).

sql-server2005中是否有任何方法可以自动分配具有最小可用数量的pk字段.
现在,我正在以编程方式执行此操作(在按钮click事件中,从表中读取所有ID,并以实用的方式计算此ID,然后插入具有该ID的新项目.)
这可能会导致并发,因为在获取值和使用该值插入新项目之间存在计算间隙

My table values are follows.

Id(pk) Item
1 Laptop
2 Pendrive
5 Mouse
======================
When I insert a new item to the table, it should assign a No.3 as ID (ie.Miimum Number available).

Is there any way in the sql-server2005 to auto-assign the pk-field with minimum available number.
Now I am doing it programatically (in the button click event read all the ID from the table and computing this ID prgramatically and inserting new item with this ID.)
This may cause cuncurrency because there is gap for computation between fetching the value and inserting new item with this value

推荐答案

否.
SQL Server将始终分配顺序号,并且不会自动返回以填补空白".
这样做的原因是,如果您以前有其他表引用了该ID,那么最好让它们挂起"而没有要引用的内容,而不是在创建新记录时自动将其与之关联.
No.
SQL server will always assign sequential numbers and will not automatically go back to "fill in the gaps".
The reasoning for this is that if you have other tables which referred to that ID previously, it is better to have them "hanging" with nothing to reference than to be automatically associated with a new record when it is created.


这篇关于主键自动分配,可用数量最少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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