简体   繁体   English

从表中获取最后一条记录 ID 的最安全方法

[英]Safest way to get last record ID from a table

In SQL Server 2008 and higher what is the best/safest/most correct way在 SQL Server 2008 及更高版本中,最好/最安全/最正确的方法是什么

  1. to retrieve the ID (based on autoincrementing primary key) out of the database table?从数据库表中检索 ID(基于自动递增的主键)?
  2. to retrieve the value of the last row of some other column (like, SELECT TOP 1 FROM Table ORDER BY DESC)?检索其他列的最后一行的值(例如,SELECT TOP 1 FROM Table ORDER BY DESC)?
SELECT IDENT_CURRENT('Table')

You can use one of these examples:您可以使用以下示例之一:

SELECT * FROM Table 
WHERE ID = (
    SELECT IDENT_CURRENT('Table'))

SELECT * FROM Table
WHERE ID = (
    SELECT MAX(ID) FROM Table)

SELECT TOP 1 * FROM Table
ORDER BY ID DESC

But the first one will be more efficient because no index scan is needed (if you have index on Id column).但是第一个会更有效,因为不需要索引扫描(如果您在 Id 列上有索引)。

The second one solution is equivalent to the third (both of them need to scan table to get max id).第二个解决方案相当于第三个(它们都需要扫描 table 以获得 max id)。

1.  SELECT MAX(Id) FROM Table

Safest way will be to output or return the scope_identity() within the procedure inserting the row, and then retrieve the row based on that ID.最安全的方法是在插入行的过程中输出或返回 scope_identity(),然后根据该 ID 检索行。 Use of @@Identity is to be avoided since you can get the incorrect ID when triggers are in play.应避免使用@@Identity,因为在触发器运行时您可能会得到错误的 ID。

Any technique of asking for the maximum value / top 1 suffers a race condition where 2 people adding at the same time, would then get the same ID back when they looked for the highest ID.任何要求最大值/前 1 的技术都会遇到竞争条件,即 2 个人同时添加,然后在他们寻找最高 ID 时会得到相同的 ID。

You can try:你可以试试:

SELECT id FROM your_table WHERE id = (SELECT MAX(id) FROM your_table)

Where id is a primary key of the your_table其中idyour_table的主键

I think this one will also work:我认为这也将起作用:

SELECT * FROM ORDER BY id DESC LIMIT 0 , 1 SELECT * FROM ORDER BY id DESC LIMIT 0 , 1

One more way -还有一种方式——

select * from <table> where  id=(select max(id) from <table>)

Also you can check on this link -您也可以查看此链接 -

http://msdn.microsoft.com/en-us/library/ms175098.aspx http://msdn.microsoft.com/en-us/library/ms175098.aspx

如果你的意思是选择最后插入的记录的 ID,它的

SELECT @@IDENTITY FROM table

SELECT LAST(row_name) FROM table_name

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

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