identity in sql server 批量插入history
- The
@@identity
function returns the last identity created in the same session. - The
scope_identity()
function returns the last identity created in the same session and the same scope. - The
ident_current(name)
returns the last identity created for a specific table or view in any session. - The
identity()
function is not used to get an identity, it's used to create an identity in aselect...into
query.
The session is the database connection. The scope is the current query or the current stored procedure.
A situation where the scope_identity()
and the @@identity
functions differ, is if you have a trigger on the table. If you have a query that inserts a record, causing the trigger to insert another record somewhere, the scope_identity()
function will return the identity created by the query, while the @@identity
function will return the identity created by the trigger.
So, normally you would use the scope_identity()
function.
No, SCOPE_IDENTITY()
only gives you the one, latest inserted IDENTITY
value. But you could check out the OUTPUT
clause of SQL Server ....
DECLARE @IdentityTable TABLE (SomeKeyValue INT, NewIdentity INT) INSERT INTO [MyTable] OUTPUT Inserted.Keyvalue, Inserted.ID INTO @IdentityTable(SomeKeyValue, NewIdentity) VALUES ('1'), ('2'), ('3')
Once you've run your INSERT
statement, the table variable will hold "some key value" (for you, to identify the row) and the newly inserted ID
values for each row inserted. Now go crazy with this! :-)
其中Inserted是和Output有关系的
UPDATE OUTPUT into a variable
Because an update can affect multiple rows, it requires a table to store its results:
declare @ids table (id int);
UPDATE Foo
SET Bar = 1
OUTPUT INSERTED.Id INTO @ids
WHERE Baz = 2
If you're sure only one row will be affected, you can pull out the id like:
declare @id int
select top 1 @id = id
from @ids
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2015-01-02 .NET Framework 系统要求
2015-01-02 System.IO命名空间下常用的类