如何设置 SQL Server 来生成分组索引?
假设我在数据库中有一个 Projects
表来跟踪活动项目,以及一个 Tasks
表来跟踪每个 的
。每个表都有一个正常的自动生成的主键,但是我也希望每个任务都有一个相对于 Tasks
项目Project
的 TaskNumber
。因此,当将任务
添加到项目
时,它们会被分配从001、002、003等递增的编号,每个项目从001开始。
首先,我认为我可以为每个 Project
存储一个 NextTaskNumber
字段。但是,在任何人有机会添加新任务并增加 NextTaskNumber
字段之前,多个人可能会从数据库请求相同的编号。我不想在 Project
中出现重复的任务编号。
更新
感谢您迄今为止的回答,但我忘记提及一个关键点。我实际上是通过 NHibernate 访问数据库,而不是直接通过 SQL 命令。那么有没有办法通过N Hibernate映射来做到这一点呢?或者,我可以在数据库上设置一个触发器,以便在创建新任务时填充任务编号字段吗?
Say I have a Projects
table in a database to track active projects, as well as a Tasks
table that tracks the Tasks
for each Project
. Each table has a normal auto generated primary key, however I also want to each task to have a TaskNumber
relative to the Project
. Thus as Tasks
are added to a Project
they are assigned incrementing numbers from 001, 002, 003 etc, starting at 001 for each project.
First I thought I could store a NextTaskNumber
field with each Project
. However, it would be possible for multiple people to request the same number from the database before any have a chance to add their new task and increment the NextTaskNumber
field. I don't want to end up with duplicate Task numbers with in a Project
.
Update
Thanks for the answers so far but I forgot to mention one critical point. I'm actually accessing the database through NHibernate not directly through SQL commands. So is there a way to do this through N Hibernate mapping? Or alternatively could I setup a trigger on the database to populate the task number field when a new task is created?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用您的 NextTaskNumber 想法如果您对代码有足够的控制权,以便您可以强制执行任务表插入操作的部分使用包含读取 NextTaskNumber 的事务、创建任务行,然后更新 NextTaskNumber。事务应该锁定数据,这样就不会出现重复的 TaskNumber 条目。
You can use your NextTaskNumber idea if you have control enough over the code so that you can force the piece that does the inserts to the Task table to use a transaction that includes the reading of NextTaskNumber, the creation of the Task row, and then the updating of NextTaskNumber. The transaction should lock the data so that you won't have duplicate TaskNumber entries.
以下代码是我通常的“我刚刚醒来”的责任:
单次插入
多次插入
创建视图
使用以下查询创建视图:
SQL Server Denali
SQL Server Denali 允许您创建序列。每个项目可以有多个序列,尽管这并不是真正使用它们的正确方法。
The following code is subject to my usual "I just woke up" liabilities:
Single Insert
Multiple Insert
Create a View
Create a view with with following query:
SQL Server Denali
SQL Server Denali allows you to create sequences. You could have multiple sequences per project, although this isn't really the right way to use them.