C#+ SQL Server ExecuteScalar()没有返回最后插入的id

jho*_*ars 9 c# sql-server

我有以下函数执行查询并在成功时返回true,在失败时返回false.不,我想扩展该方法,以便在每个触发的插入查询中,类var insertId包含最后插入的行的ID.

问题是它insertId始终为0,所以不知何故executeScalar()不返回ID.

有任何想法吗?或其他解决方案来获取最后一个插入查询的ID ....

    public int insertId;        

    public bool executeCommand(string q) {
        q += "; SELECT @@IDENTITY AS LastID";
        bool retour = true;
        SqlConnection myCon = new SqlConnection(Settings.DSN);
        SqlCommand cmd = new SqlCommand(q, myCon);
        try {
            cmd.Connection.Open();
            insertId = (int)cmd.ExecuteScalar();
            if (insertId > 0) {
                MessageBox.Show(insertId.ToString());
            }

            myCon.Close();
        } catch (Exception ex) {
            this.error = ex.Message;
            retour = false;
        }
        return retour;
    }
Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 19

您应该立即更改您的INSERT插入ID(在OUTPUT子句中)!这适用于SQL Server 2005 - 该OUTPUT子句在SQL Server 2000或更早版本中不可用(您没有指定您在问题中使用的SQL Server 版本 ...).阅读有关OUTPUTMSDN联机丛书中条款的更多信息.

将插入更改为:

INSERT INTO dbo.YourTable(Col1, Col2, ..., ColN)   
OUTPUT Inserted.ID
VALUES(Val1, Val2, ..., ValN);
Run Code Online (Sandbox Code Playgroud)

然后当你从C#执行insert语句时,你应该能够做到:

using(SqlCommand cmdInsert = new SqlCommand("INSERT.....", myCon))
{
   myCon.Open();
   var result = cmdInsert.ExecuteScalar();
   myCon.Close();
}
Run Code Online (Sandbox Code Playgroud)

并且您的result变量现在应该包含正确的,新插入的值!