如何在 MS SQL 2008 中获取下一行号
如果有人可以向我展示如何在 SQL Server 2008 中获取数据库表中下一个可用的可用行号,我将不胜感激。
我想做的是实现类似于 Oracle 的东西,其中序列号给出新行的下一个数字。在互联网上搜索,我没有找到任何与此匹配的内容,但我找到的是 row_number()
。不幸的是,我无法让它在 insert
语句中工作。
I would be grateful if someone could show me how in SQL Server 2008
you can get the next free available row number in a database table?
What I am trying to do is implement something similar to Oracle
where sequence numbers give the next number for a new row. Searching the internet, I haven't found anything that matches this, but what I have found is row_number()
. Unfortunately, I cannot make it work within a insert
statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您正在寻找的是列的 IDENTITY 属性 。使用它可以让 SQL Server 自动分配您所说的行号。
使用
id
作为 IDENTITY 列的简单示例:I think what you're looking for is the IDENTITY property for a column. Using that allows SQL Server to auto-assign what you're calling row numbers.
A quick example using
id
as an IDENTITY column:将上面的代码包装在一个事务中,然后就可以开始了。
Wrap the above code in a transaction and you are good to go.
您真的想要行号还是只是寻找 ID。
在这种情况下,请查找标识列和 sql server。
http://www.dotnetfunda.com/articles/article753 -identity-columns-in-sql-server.aspx
或:http://www.sqlteam.com/article/autonumbering-identity-columns
在这些情况下,在插入语句中您不指定 ID,sql server 会自动提供一个新 ID。
成功
Do you really want the row number or are you just looking for an ID.
In that case, look for identity columns and sql server.
http://www.dotnetfunda.com/articles/article753-identity-columns-in-sql-server.aspx
or: http://www.sqlteam.com/article/autonumbering-identity-columns
In these cases, in your insert statement you do not specify the ID and sql server automatically provides a new one.
Succes
创建表时必须设置标识字段。然后,当您插入其中时,您会跳过该字段。插入就像假设身份字段称为 table1id:
现在身份有一些限制。即使操作回滚或者记录被删除,它也会用完一个数字,因此不会重新使用它,因此会出现间隙。这应该不重要,因为代理 ID 无论如何都不应该具有商业意义。
You have to set up the identity field when you create the table. Then when you insert into it, you skip that field. An insert would be something like assuming the identity field is called table1id:
Now identity has some limitations. It will use up a number even if the action is rolled back or if the record is deleted it will not re-use it, so there will be gaps. That should not be important as a surrogate id shouldn't have business meaning anyway.