从表中获取最后一条记录 ID 的最安全方法 [英] Safest way to get last record ID from a table

查看:31
本文介绍了从表中获取最后一条记录 ID 的最安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 SQL Server 2008 及更高版本中,最好/最安全/最正确的方法是什么

In SQL Server 2008 and higher what is the best/safest/most correct way

  1. 从数据库表中检索 ID(基于自动递增的主键)?
  2. 要检索其他列的最后一行的值(例如,SELECT TOP 1 FROM Table ORDER BY DESC)?

推荐答案

最安全的方法是在插入行的过程中输出或返回 scope_identity(),然后根据该 ID 检索行.应避免使用@@Identity,因为在触发器运行时您可能会得到错误的 ID.

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.

任何要求最大值/前 1 名的技术都会遇到竞争条件,即 2 个人同时添加,然后在他们寻找最高 ID 时会得到相同的 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.

这篇关于从表中获取最后一条记录 ID 的最安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆