Getting new IDs after insert(插入后获取新 ID)
问题描述
我将一堆新行插入到定义如下的表中:
I'm inserting a bunch of new rows into a table which is defined as follows:
CREATE TABLE [sometable](
[id] [int] IDENTITY(1,1) NOT NULL,
[someval] sometype NOT NULL
)
使用以下插入:
insert into sometable select somefield as someval from othertable
完成后,我想知道所有新插入的行的 ID.SCOPE_IDENTITY()
只返回最后插入的 ID 行.
when I've finished, I'd like to know the IDs of all the newly inserted rows. SCOPE_IDENTITY()
only returns the ID last row inserted.
如何获取所有新 ID?
How can I get all the new IDs?
想到的一种方法是从 sometable 和插入后的 scope_identity() 中获取当前最大的标识,并使用这两个值从 sometable 中进行选择.例如:
One method that springs to mind would be to grab the current largest identity from sometable and the scope_identity() post-insert, and use these two values to select from sometable. For example:
declare @currentMaxId int;
select @currentMaxId=MAX(id) from sometable
insert into sometable select somefield as someval from othertable
select * from sometable where id>@currentMaxId and id<=SCOPE_IDENTITY()
有更好的模式吗?
推荐答案
使用 OUTPUT 功能将所有 INSERTED Id 抓取回表中.
Use the OUTPUT functionality to grab all the INSERTED Id back into a table.
CREATE TABLE MyTable
(
MyPK INT IDENTITY(1,1) NOT NULL,
MyColumn NVARCHAR(1000)
)
DECLARE @myNewPKTable TABLE (myNewPK INT)
INSERT INTO
MyTable
(
MyColumn
)
OUTPUT INSERTED.MyPK INTO @myNewPKTable
SELECT
sysobjects.name
FROM
sysobjects
SELECT * FROM @myNewPKTable
这篇关于插入后获取新 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:插入后获取新 ID


基础教程推荐
- 带更新的 sqlite CTE 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01