Using OUTPUT/INTO within instead of insert trigger invalidates 'inserted' table

白昼怎懂夜的黑 提交于 2019-12-04 06:23:11

You haven't specified what your 'clients' are, but if they are a .Net or similar app, you simply need to drop the INTO portion of your output. Your clients can't see the results because they are not being returned in the result set.

Your trigger then should look like this:

create trigger [trMyTableInsert] on [MyTable] instead of insert
as
BEGIN

 INSERT INTO [MyTable]
      ([MyBit])
   OUTPUT inserted.MyID,
          inserted.MyBit
   SELECT inserted.MyBit
     FROM inserted;

 -- LOGIC NOT SHOWN HERE THAT USES @InsertedRows
END;

This causes inserts to behave like a select query as far as the client is concerned - you can iterate over the results to get the identity value (or other special values like Timestamp).

This is how LinqToSql supports identity columns with instead of insert triggers.

the culprit here is actually the identity column; if you replace it with a sequence then everything just works™

create sequence testing_id as int start with 1 increment by 1

create table testing (id int default (next value for testing_id), s varchar(100))

create trigger tr_testing on testing instead of insert as
begin
    declare @inserted table (id int, s varchar(100))
    insert into testing
    output inserted.* into @inserted
    select * from inserted
end

declare @inserted table (id int, s varchar(100))
insert into testing (s)
output inserted.* into @inserted
values ('testing1'),('testing2')

select * from @inserted
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!