2

This trigger:

ALTER TRIGGER InsteadTrigger on CustomerView INSTEAD OF INSERT AS BEGIN SET NOCOUNT ON; INSERT INTO Person SELECT FirstName, LastName FROM inserted 

Causes this query to return null.

INSERT INTO CustomerView (FirstName, LastName) Values ('Jonathan', 'Allen') SELECT SCOPE_IDENTITY() 

Is there a way to fix the trigger so that SCOPE_IDENTITY will return the correct value? (I can't use @@IDENTITY because there may be other triggers on the table involved.)

5
  • P.S. My customer is asking about this. I would never intentionally get myself into this situation. Commented Feb 3, 2012 at 21:02
  • First off, your making the very common error of assuming the INSERT would only process one row. Multiple rows can be inserted by a single insert statement. Commented Feb 3, 2012 at 21:07
  • 1
    No I'm not. The trigger will work for multiple rows and no one expects SCOPE_IDENTITY to work unless you only inserted one. Commented Feb 3, 2012 at 21:08
  • possible duplicate of SQL Server list of insert identities Commented Feb 3, 2012 at 21:08
  • 1
    @JoeStefanelli - That doesn't work here. I was going to suggest the OUTPUT clause but it always seems to return 0 in my test. It does the OUTPUT clause before generating the identity Test script here Commented Feb 3, 2012 at 21:09

1 Answer 1

3

No I don't think this is possible.

You can return it from the trigger itself of course.

ALTER TRIGGER InsteadTrigger on CustomerView INSTEAD OF INSERT AS BEGIN SET NOCOUNT ON; INSERT INTO Person SELECT FirstName, LastName FROM inserted SELECT SCOPE_IDENTITY() AS PersonId END 

And you can use CONTEXT_INFO to suppress the result set except for when you require it.

Using the OUTPUT clause doesn't work in this context as discussed in this Microsoft Connect Item it is evaluated before the insert into the main table and so before the IDENTITY function is called.

Sign up to request clarification or add additional context in comments.

1 Comment

Not great, but then again neither is this whole situation. At this time I do believe this is the best that they can hope for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.