简体   繁体   English

表中的最后一个id值。 SQL Server

[英]Last id value in a table. SQL Server

Is there a way to know the last nth id field of a table, without scanning it completely? 有没有办法知道最后的nth表的id字段,而没有完全扫描呢? (just go to the end of table and get id value) (只是到表的末尾获取id值)

table
id   fieldvalue
1    2323
2    4645
3    556
...  ...
100000000  1232

So for example here n = 100000000 100 Million 所以例如这里n = 100000000亿

--------------EDIT----- So which one of the queries proposed would be more efficient? --------------编辑-----那么提出的哪一个查询会更有效率?

SELECT MAX(id) FROM <tablename>

Assuming ID is the IDENTITY for the table, you could use SELECT IDENT_CURRENT('TABLE NAME') . 假设ID是表的IDENTITY,您可以使用SELECT IDENT_CURRENT('TABLE NAME')

See here for 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> 关于这种方法需要注意的一件事:如果INSERT失败但增加了IDENTITY计数器,那么你将得到一个高于SELECT MAX(id) FROM <tablename>返回的结果的结果。

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

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行,然后插入依赖于table1 id的table2行,则可以使用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行时,这才有效

First of all, you want to access the table in DESCENDING order by ID. 首先,您希望按ID以DESCENDING顺序访问该表。

Then you would select the TOP N records. 然后你会选择TOP 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个记录,并且最有可能最终被优化为单个记录提取。

选择Ident_Current('您的表名')给出表的最后一个ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM