@@IDENTITY after INSERT statement always returns 0

后端 未结 13 1177
一整个雨季
一整个雨季 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:03

    As you're using Access, take a look at this article from aspfaq, scroll down to about half way down the page. The code's in classic ASP, but hopefully the principles should still stand.


    The SELECT @@Identity ends up being treated as a separate execution context, I believe. Code that should work would be:

    public int ExecuteInsertStatement(string statement)
    {
        InitializeAndOpenConnection();
    
        IDbCommand cmdInsert = connection.CreateCommand();
        cmdInsert.CommandText = statement + "; SELECT @@Identity";
        object result = cmdInsert.ExecuteScalar();
    
        if (object == DBNull.Value)
        {
           return -1;
        }
        else
        {
           return Convert.ToInt32(result);
        }
    }
    

    You'd probably want/need to tidy up the concatenation that adds the 'SELECT @@Identity' onto the end of the code though.

提交回复
热议问题