vgk
vgk

Reputation: 13

tsql return identity values when inserting multiple records into a view

I have a situation where I need to insert multiple records/batch insert into a view which has instead of trigger. How can I retrieve the inserted identity values? I tried using the OUTPUT clause to retrieve the Id from the Inserted table but it always returns null.

Upvotes: 1

Views: 1655

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 138970

Using this setup.

create table InsteadOf
(
  ID int identity primary key,
  Name varchar(10) not null
)

go

create view v_InsteadOf
as
select ID, Name
from InsteadOf

go

create trigger tr_InsteadOf on InsteadOf instead of insert
as
begin
  insert into InsteadOf(Name)
  select Name
  from inserted
end

The statement

insert into v_InsteadOf(Name)
output inserted.*
select 'Name1' union all 
select 'Name2'

Will give you an error.

Msg 334, Level 16, State 1, Line 4 The target table 'InsteadOf' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause.

Using an INTO clause with the insert instead.

declare @IDs table(ID int, Name varchar(10))

insert into v_InsteadOf(Name)
output inserted.* into @IDs
select 'Name1' union all 
select 'Name2'

select *
from @IDs

Gives you 0 as a value not null.

ID          Name
----------- ----------
0           Name1
0           Name2

You can put the output clause in the trigger.

create trigger tr_InsteadOf on InsteadOf instead of insert
as
begin
  insert into InsteadOf(Name)
  output inserted.*
  select Name
  from inserted
end

And the output will be generated for you when you do the insert.

insert into v_InsteadOf(Name)
select 'Name1' union all 
select 'Name2'

Result:

ID          Name
----------- ----------
1           Name1
2           Name2

Update:
To capture the output from the insert statement you can use insert into ... exec (...)

declare @T table
(
  ID int,
  Name varchar(10)
)

insert into @T
exec
  (
    'insert into v_InsteadOf(Name)
     values (''Name1''),(''Name2'')'
  )

Upvotes: 1

Related Questions