如何在插入时获取最后一行的自动增量值 [英] How to get the value of autoincrement of last row at the insert

查看:38
本文介绍了如何在插入时获取最后一行的自动增量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用谷歌搜索了这个问题一个星期,但没有任何有用的东西,我认为我没有使用正确的词

I have googled this problem one week and no thing useful I think am not using the correct word

我正在使用带有 t-sql 的 SQL Server 2008,我需要在插入新行时优化我的函数.

I am using SQL Server 2008 with t-sql and my need is to optimise my function when I insert a new row.

我有一个表,第一列是整数自增类型的键,其他列仅供参考

I have a table with first column is the key of integer autoincrement type and other columns are just for information

当我们进行插入时,SQL Server 会自动增加键,我必须做一个 select max 来获取值,所以有没有像 @@IDENTITY 这样的全局变量或函数避免开始结束事务并选择最大

When we do an insert, SQL Server increments the key automatically and I have to do a select max to get the value, so is there a way like a global variable like @@IDENTITY or a function to avoid the begin end transaction and select max

推荐答案

使用 SCOPE_IDENTITY:

-- do insert

SELECT SCOPE_IDENTITY();

哪个会给你:

插入到标识列中的最后一个标识值相同的范围.作用域是一个模块:存储过程、触发器、功能,或批处理.因此,如果两个语句在同一范围内它们在同一个存储过程、函数或批处理中.

The last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

这篇关于如何在插入时获取最后一行的自动增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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