@@IDENTITY after INSERT statement always returns 0

后端 未结 13 1176
一整个雨季
一整个雨季 2021-01-11 13:00

I need a function which executes an INSERT statement on a database and returns the Auto_Increment primary key. I have the following C# code but, while the INSERT statement w

相关标签:
13条回答
  • 2021-01-11 13:16

    I think you need to have the Select @@identity with the first create command - try appending it via ";SELECT @@Identity" and .ExecuteScalar the insert statement

    0 讨论(0)
  • 2021-01-11 13:18

    Are there any triggers on your table that might be inserting into other tables? Generally we're advised against using @@Identity in favour of IDENT_CURRENT so that you can guarantee that the identity returned is for the table you just inserted into.

    0 讨论(0)
  • 2021-01-11 13:19

    You are using Jet (not SQL Server) and Jet can only handle one SQL statement per command, therefore you need to execute SELECT @@IDENTITY in a separate command, obviously ensuring it uses the same connection as the INSERT.

    0 讨论(0)
  • 2021-01-11 13:24

    Check your database settings. I had a similar problem a while ago and discovered that the SQL Server connection setting 'no count' was enabled.

    In SQL Server Management Studio, you can find this by right-clicking the server in the Object Explorer, select Properties and then navigate to the Connections page. Look at the settings for "Default connection options"

    0 讨论(0)
  • 2021-01-11 13:26

    Microsoft.Jet.OLEDB.4.0 provider supports Jet v3 and Jet v4 database engines, however SELECT @@IDENTITY is not supported for Jet v3.

    MSAccess 97 is Jet v3 and does not support SELECT @@IDENTITY; It supported on MSAccess 2000 and above.

    0 讨论(0)
  • 2021-01-11 13:26

    I think that @@identity is valid only in the scope of the command - in your case when you execute "statement".

    Modify your "statement"so that the stored procedure itself will return the @@IDENTITY value right after the INSERT statement, and read it as the return code of the stored procedure execution.

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