I was trying to insert a new row into two tables which has a relationship between. I wrote the stored procedure as follows.
ALTER PROCEDURE InsertUserProfile
@Richard Its "ID" which is the Auto Increment in both tables.
Having an auto-increment (IDENTITY
) act as a primary key is fine, but using it as a foreign key is dangerous, since you can't really guarantee that they will always be in sync; any rollback could leave them broken (rollback does not undo identity increments, as this would affect other SPIDs). Also, any thread-race between two concurrent INSERT
s will be in jeopardy.
The correct approach here is to query SCOPE_IDENTITY()
after the first insert, and use that in the INSERT
to the second table; i.e. in the second table you tell it the value. Note that since @@ERROR
and SCOPE_IDENTITY()
are floating values, you should query them both directly after the first INSERT
:
SELECT @Error = @@ERROR, @NewId = SCOPE_IDENTITY()