0

我正在向现有数据库表添加一个触发器,该表由我未编写代码的应用程序使用,并且无法更改其中的代码。

我想将一些信息从TableAinto插入TableB到.INSERTTableA

  1. 应用程序运行INSERT INTO TableA<-- 此更新@@identity
  2. 运行的ON INSERT触发器TableA然后将数据插入到TableB<- 这也@@identity使用新值更新
  3. 应用程序读取@@identity<-- 这TableB不是TableA应用程序所期望的

有什么方法可以不更新@@identity触发器中的from 吗?

4

1 回答 1

2

....因为@@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
于 2020-12-01T01:14:28.997 回答