How to get a table identity inserted by instead of insert trigger?

前端 未结 2 1666
天涯浪人
天涯浪人 2021-01-22 07:18

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         


        
相关标签:
2条回答
  • 2021-01-22 08:02

    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.

    0 讨论(0)
  • 2021-01-22 08:12

    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:

    1. Find some way to eliminate the need for that instead of trigger.
      This is my best recommendation.

    2. 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.

    3. Find some way of passing data between the stored procedure and the instead of trigger. Since triggers can't except or return parameters, you will have to use either a temporary table or a regular table. This suggested solution is only suggested as a last resort, since it will complicate your code and probably cause some performance issues as well. Also, you will have to find a way to hold execution of the stored procedure until the instead of trigger will finish it's work. I can give you some pointers on how to share data between the procedure and the trigger, but I really suggest not to choose this solution.
    0 讨论(0)
提交回复
热议问题