Instead of trigger in SQL Server loses SCOPE_IDENTITY?

后端 未结 6 2064
走了就别回头了
走了就别回头了 2020-12-01 10:30

I have a table where I created an INSTEAD OF trigger to enforce some business rules.

The issue is that when I insert data into this table, SCOPE_I

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 11:35

    A little late to the party, but I was looking into this issue myself. A workaround is to create a temp table in the calling procedure where the insert is being performed, insert the scope identity into that temp table from inside the instead of trigger, and then read the identity value out of the temp table once the insertion is complete.

    In procedure:

    CREATE table #temp ( id int )
    
    ... insert statement ...
    
    select id from #temp
    -- (you can add sorting and top 1 selection for extra safety)
    
    drop table #temp
    

    In instead of trigger:

    -- this check covers you for any inserts that don't want an identity value returned (and therefore don't provide a temp table)
    IF OBJECT_ID('tempdb..#temp') is not null
    begin
        insert into #temp(id)
        values
        (SCOPE_IDENTITY())
    end
    

    You probably want to call it something other than #temp for safety sake (something long and random enough that no one else would be using it: #temp1234235234563785635).

提交回复
热议问题