Sql server 合并中的更新行为不同?它没有';插入时无法获取上下文信息()
我创建了以下两个带有触发器的测试表来记录所有操作(插入、删除和更新) 设置表和触发器:Sql server 合并中的更新行为不同?它没有';插入时无法获取上下文信息(),sql-server,Sql Server,我创建了以下两个带有触发器的测试表来记录所有操作(插入、删除和更新) 设置表和触发器: -- drop table test; drop table testLog create table test (id int identity primary key, x int); create table testLog (idx int identity primary key, Action varchar(10), id int not null, x_deleted int, x_
-- drop table test; drop table testLog
create table test (id int identity primary key, x int);
create table testLog (idx int identity primary key, Action varchar(10), id int not null,
x_deleted int, x_inserted int, uid uniqueidentifier);
go
-- Trigger to log the changes
create trigger trigger_test on test
after insert, delete, update
as
declare @id uniqueidentifier = context_info();
print @id;
insert testLog (id, Action, x_deleted, x_inserted, uid)
select isnull(d.id, i.id) ,
case when i.id is not null and d.id is not null then 'Updated'
when d.id is not null then 'Deleted'
when i.id is not null then 'Inserted'
end ,
d.x ,
i.x ,
@id
from Deleted d
full outer join inserted i on i.id = d.id;
set context_info 0;
go
现在插入一些示例数据
set context_info 0
insert test (x) values (10), (20), (30), (40), (50);
SELECT * FROM test;
SELECT * FROM testLog
go
下面的语句工作正常。正确的context\u info()
保存在日志表中
begin tran
declare @newid uniqueidentifier = newid()
--
set context_info @newid
print @newid
insert test(x) values (1)
set context_info @newid
update test set x = 2 where id = 1
SELECT * FROM dbo.testLog;
rollback
go
但是,只有插入部分的合并
在上下文信息()中获得了值。
最近两次更新的
uid
为零 不要在触发器中将上下文信息设置为零。首先,你为什么要这么做?触发器不负责“清理”。merge语句将导致触发器分别为插入和更新执行。您没有注意到结果窗格中的多个“打印”吗?这应该是一个大线索
begin tran
declare @newid uniqueidentifier = newid()
--
set context_info @newid
print @newid;
with v as (select * from (values (1, 11), (2, 22), (6, 66)) v (id, x))
merge test as t using v on t.id = v.id
when matched then update set x = v.x
when not matched by target then insert (x) values (x);
SELECT * FROM dbo.testLog;
rollback
go