How to use SCOPE_IDENTITY to retrieve the last ID that was inserted

前端 未结 2 1644
悲哀的现实
悲哀的现实 2020-12-19 00:45

Suppose I have two table. First table\'s primary key is the foreign key for another table.

Table Member has its primary key as the foreign key in

相关标签:
2条回答
  • 2020-12-19 01:25

    SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope.

    Given you have 2 tables:

    Member: id int (primaryKey), name varchar
    
    Member_Detail: id int (primaryKey), pk int (foreignKey), name varchar
    

    You can do this:

    DECLARE @MemberId int
    
    INSERT INTO Member (name) VALUES ('hello');
    
    SET @MemberId = SCOPE_IDENTITY()
    
    INSERT INTO Member_Detail (pk, name) VALUES (@MemberId, 'hello again')
    

    MSDN Reference:

    SCOPE_IDENTITY (Transact-SQL)

    Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

    0 讨论(0)
  • 2020-12-19 01:29

    I've seen "funny" behavior with scope_identity. As a result, I like to use an output clause. Here's an example:

    declare @id table (i int)
    insert into Member (name) values ('NightKnight')
    output (MemberId) into @id
    
    select * from @id
    
    0 讨论(0)
提交回复
热议问题