I'm inserting values into a view which has an INSTEAD OF trigger to insert/update various other tables. The final line of the trigger is
SELECT SCOPE_IDENTITY()
which means that when I select SCOPE_IDENTITY()
myself after the insert so I can use the just inserted identity value I get a NULL value.
If I understand it correctly, this is because there is no identity value associated with the SCOPE_IDENTITY()
that was just called.
Is there a way to get the SELECT value from the trigger? Changing the trigger is not really an option due to other dependencies on its current behaviour.
I could do it with a temp table and executing the insert as dynamic SQL but that seems like a horribly hacky way to do it:
DECLARE @scopeid INT
CREATE TABLE #temp(id int)
INSERT INTO #temp EXEC ('INSERT INTO myView(somecolumns) VALUES (somevalues)')
SELECT @scopeid = TOP 1 id FROM #temp
DROP TABLE #temp
Surely there's a neater way than this?