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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3422168/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:07:17  来源:igfitidea点击:

Safest way to get last record ID from a table

sqlsql-serversql-server-2008

提问by mare

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?
  2. to retrieve the value of the last row of some other column (like, SELECT TOP 1 FROM Table ORDER BY DESC)?
  1. 从数据库表中检索 ID(基于自动递增的主键)?
  2. 检索其他列的最后一行的值(例如,SELECT TOP 1 FROM Table ORDER BY DESC)?

采纳答案by Andrew

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. Use of @@Identity is to be avoided since you can get the incorrect ID when triggers are in play.

最安全的方法是在插入行的过程中输出或返回 scope_identity(),然后根据该 ID 检索行。应避免使用@@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。

回答by gyromonotron

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)。

回答by Michael Pakhantsov

1.  SELECT MAX(Id) FROM Table

回答by Hara Das

You can try:

你可以试试:

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

Where idis a primary key of the your_table

id主键在哪里your_table

回答by Pelingier

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

回答by Sachin Shanbhag

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

回答by Iain Ward

And if you mean select the ID of the last record inserted, its

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

SELECT @@IDENTITY FROM table