....因为@@identity 没有范围,您可以创建自己的范围,该范围在触发器结束时带有@@identity 值
create table tableA(idA int identity(100, 1), colA int)
go
create table tableB(idB int identity(1000, 1), colB int)
go
create trigger triggerA on tableA
for insert
as
begin
if not exists(select * from inserted)
begin
return;
end
declare @tableA@@identity int = @@identity;
select @@identity as [@@identity_triggerA_in];
--add rows to tableB
insert into tableB(colB)
select object_id
from sys.all_objects
select @@identity as [@@identity_after_insert_in_tableB];
if @tableA@@identity is not null
begin
declare @sql varchar(100) = concat('create table #t(id int identity(', @tableA@@identity, ',1)); insert into #t default values');
exec (@sql);
end
select @@identity as [@@identity_triggerA_out];
end
go
insert into tableA(colA) values (10);
select @@identity;
go
insert into tableA(colA)
select top (200) 1
from sys.all_objects;
select @@identity;
go
insert into tableA(colA)
select 1
where 1=2;
select @@identity;
go
drop table tableA;
go
drop table tableB;
go