How to get the value of autoincrement of last row at the insert(如何在插入时获取最后一行的自动增量值)
问题描述
我用谷歌搜索了这个问题一个星期,但没有任何有用的东西,我认为我没有使用正确的词
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.
这篇关于如何在插入时获取最后一行的自动增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在插入时获取最后一行的自动增量值
基础教程推荐
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 无法解决整理冲突 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
