Retrieving the value of RETURN @@IDENTITY in C#

后端 未结 5 1860
说谎
说谎 2021-01-20 03:22

Here\'s a very simple question. I have an SP that inserts a row into a table and at the end there\'s the statement RETURN @@IDENTITY. What I can\'t seem to find is a way to

相关标签:
5条回答
  • 2021-01-20 04:03

    One point to mention. You should really use SCOPE_IDENTITY to return the identity value after INSERT. There is potential for @@IDENTITY to return the wrong value. Especially if TRIGGERS are in use, writing value to other tables after INSERT.

    See the Books Online page for more detail.

    0 讨论(0)
  • 2021-01-20 04:07

    BTW, in most circumstances, you should use SCOPE_IDENTITY() rather than @@IDENTITY. Ref.

    0 讨论(0)
  • 2021-01-20 04:15
    Dim c as new sqlcommand("...")
    
    Dim d As New SqlParameter()
    d.Direction = ParameterDirection.ReturnValue
    c.parameters.add(d)
    
    c.executeNonQuery
    
    (@@IDENTITY) = d.value
    

    It is more or less like this...either this or just return the value from a stored procedure as an output parameter.

    0 讨论(0)
  • 2021-01-20 04:16

    Sounds to me like you want to execute with a scalar value

    SqlCommand.ExecuteScalar()
    

    as others have mentioned I think using SCOPE_IDENTITY() is more secure than the @@IDENTITY variable

    0 讨论(0)
  • 2021-01-20 04:22

    Someone says use

    IDENT_CURRENT('TableName')

    http://www.velocityreviews.com/forums/t303448-return-identity-after-sql-insert.html

    -Zubair http://zubairdotnet.blogspot.com

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