Scope_identity() in batched sqlclient commands

后端 未结 1 1885
野的像风
野的像风 2021-01-24 21:28

I usually use a stored procedure when inserting records to make sure I get the correct scope_identity() value. I have a requirement to get the id field of an inserted record whe

相关标签:
1条回答
  • 2021-01-24 21:54

    From the documentation for SCOPE_IDENTITY (emphasis mine):

    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.

    In this case, your command:

    "insert into .... ; select SCOPE_IDENTITY();"
    

    Is a batch, and therefore, you will get the last inserted identity value in that batch, which in this case is the identity value in the insert, since it's the only other statement in the batch.

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