Stored Procedure to Insert Two Tables with Relationship?

前端 未结 3 363
日久生厌
日久生厌 2021-01-19 14:24

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         


        
3条回答
  •  攒了一身酷
    2021-01-19 14:57

    @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 INSERTs 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()
    

提交回复
热议问题