Stored Procedure to Insert Two Tables with Relationship?

前端 未结 3 353
日久生厌
日久生厌 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条回答
  • You need to capture the auto-incremented value that you get when you insert into the first table, tbl_user_login. After you capture it, you need to use it to insert into the second table.

    DECLARE @ID int
    
    BEGIN TRANSACTION 
    INSERT INTO tbl_user_login VALUES (@UserID, @Pass, @Enabled, @Permission, @Rank)
    
    SET @ID = SCOPE_IDENTITY()    
    IF @@ERROR <> 0
    BEGIN      
        ROLLBACK     
        RETURN 
    END   
    
    INSERT INTO tbl_user_profile VALUES (@ID, @FName, @LName, @Phone, @Email1, @Email2) 
    
    IF @@ERROR <> 0 
    BEGIN     
        ROLLBACK     
        RETURN 
    END  
    
    COMMIT 
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2021-01-19 15:00
    Create Table tbl_user_login
    (
    **ID INT Identity(1,1),**
    UserID varchar10,
    Pass varchar50 ,
    Enabled int,
    Permission int ,
    Rank int
    );
    

    Make ID column as Identity(1,1) that will be auto incremented column and that will solve your problem. Make it in both tables.

    0 讨论(0)
提交回复
热议问题