SQL 表中的最后一个 id 值。数据库服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5113450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Last id value in a table. SQL Server
提问by cMinor
Is there a way to know the last nth
id field of a table, without scanning it completely? (just go to the end of table and get id value)
有没有办法知道表的最后一个nth
id 字段,而无需完全扫描它?(只需转到表的末尾并获取 id 值)
table
id fieldvalue
1 2323
2 4645
3 556
... ...
100000000 1232
So for example here n = 100000000
100 Million
因此,例如这里n = 100000000
1 亿
--------------EDIT-----So which one of the queries proposed would be more efficient?
--------------编辑-----那么提出的哪一个查询会更有效?
回答by rayman86
SELECT MAX(id) FROM <tablename>
回答by rsbarro
Assuming ID is the IDENTITY for the table, you could use SELECT IDENT_CURRENT('TABLE NAME')
.
假设 ID 是表的 IDENTITY,您可以使用SELECT IDENT_CURRENT('TABLE NAME')
.
See herefor more info.
请参阅此处了解更多信息。
One thing to note about this approach:If you have INSERTs that fail but increment the IDENTITY counter, then you will get back a result that is higher than the result returned by SELECT MAX(id) FROM <tablename>
关于这种方法需要注意的一件事:如果您的插入失败但增加了 IDENTITY 计数器,那么您将返回一个高于返回结果的结果SELECT MAX(id) FROM <tablename>
回答by kosmo
You can also use system tables to get all last values from all identity columns in system:
您还可以使用系统表从系统中的所有标识列中获取所有最后一个值:
select
OBJECT_NAME(object_id) + '.' + name as col_name
, last_value
from
sys.identity_columns
order by last_value desc
回答by vooxo
In case when table1
rows are inserted first, and then rows to table2
which depend on ids from the table1
, you can use SELECT
:
如果table1
首先插入行,然后插入table2
依赖于 id 的行,则table1
可以使用SELECT
:
INSERT INTO `table2` (`some_id`, `some_value`)
VALUES ((SELECT some_id
FROM `table1`
WHERE `other_key_1` = 'xxx'
AND `other_key_2` = 'yyy'),
'some value abc abc 123 123 ...');
Of course, this can work only if there are other identifiers that can uniquely identify rows from table1
当然,这只有在有其他标识符可以唯一标识行的情况下才有效 table1
回答by Md Shahriar
Select Ident_Current('Your Table Name') gives the last Id of your table.
Select Ident_Current('Your Table Name') 给出表的最后一个 ID。
回答by Michael Dillon
First of all, you want to access the table in DESCENDING order by ID.
首先,您要按 ID 以 DESCENDING 顺序访问表。
Then you would select the TOP N records.
然后您将选择前 N 条记录。
At this point, you want the last record of the set which hopefully is obvious. Assuming that the id field is indexed, this would at most retrieve the last N records of the table and most likely would end up being optimized into a single record fetch.
在这一点上,您需要该集合的最后一条记录,希望这是显而易见的。假设 id 字段被索引,这最多将检索表的最后 N 条记录,并且很可能最终会被优化为单个记录提取。