Stored Procedure to Insert Two Tables with Relationship?

前端 未结 3 451
日久生厌
日久生厌 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:52

    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 
    

提交回复
热议问题