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

编程入门 行业动态 更新时间:2024-10-27 02:18:21
本文介绍了从表中获取最后一条记录 ID 的最安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

  • 从数据库表中检索 ID(基于自动递增的主键)?
  • 要检索其他列的最后一行的值(例如,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 的最安全方法

    本文发布于:2023-10-20 12:59:28,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1511036.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:方法   ID

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!