I have a problem described as follows: I have a table with one instead of insert trigger:
create table TMessage (ID int identity(1,1), dscp varchar(50))
GO
Alter
SCOPE_IDENTITY() return the value from current scope and that is stored procedure outside from stored procedure it will be null.use @@identity to get last inserted identity.
Well, you've got yourself quite a pickle there.
From the one hand, you need the instead of insert
trigger on your table, but from the other hand, you want to get the identity that this trigger generates back to the stored procedure that activated it.
Since there is no way to send parameters to and from triggers, you will have to do one of 3 things:
Find some way to eliminate the need for that instead of trigger.
This is my best recommendation.
Break your stored procedure to 2 parts: One part will do everything until the insert into
statement (including it), thus activating the instead of insert
trigger, and the other part that will do all operations needed after the trigger. this way you can use the scope_identity()
inside the instead of insert
trigger and send it's return value to the second stored procedure as a parameter.
Note: this design means you have to insert records one by one. should you try to insert more then one record, scope_identity()
will only return the identity of the last row inserted by the trigger.