使用scope_Identity()检索最后插入的ID

时间:2014-01-27 18:08:26

标签: c# asp.net sql-server-2012

我正在尝试使用SCOPE_IDENTITY插入最后一个ID,但是我收到了一个错误。 我正在使用SQL Server 2012和Visual Studio Express 2013

这是我的代码

protected void PerformInscription(string sEmail, string sPassword,string sName)
{
    bool buserIdAuthenticated = false;
    string salt = null;
    string passwordHash = pwdManager.GeneratePasswordHash(txtPassword.Text, out salt);

    SqlConnection sqlConnection;
    sqlConnection = new SqlConnection();

    try
    {
        sqlConnection.ConnectionString = sqlDataSource1.ConnectionString;

        string insertStatement = "INSERT INTO [User] "
                                 + "(email, hash, salt, name) "
                                 + "VALUES (@email, @hash, @salt, @name);"
                                 + "SELECT SCOPE_IDENTITY() AS id_user;";

        SqlCommand insertCommand = new SqlCommand(insertStatement, sqlConnection);

        insertCommand.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = sEmail;
        insertCommand.Parameters.Add("@hash", SqlDbType.VarChar, 50).Value = passwordHash;
        insertCommand.Parameters.Add("@salt", SqlDbType.VarChar, 50).Value = salt;
        insertCommand.Parameters.Add("@nom", SqlDbType.VarChar, 50).Value = sName;

        sqlConnection.Open();

        int count = insertCommand.ExecuteNonQuery();

        int User_ID = Convert.ToInt32(insertCommand.Parameters["@id_user"].Value);
        Session["Id_user"] = User_ID;

        insertCommand.Dispose();

        if (count >= 1)
        {
            buserIdAuthenticated = true;                    
            Session["userIdAuthenticated"] = buserIdAuthenticated;
            Response.Redirect("../pages/Welcome.aspx");
        }
    }

    catch (SqlException ex)
    {
        lblMessage.Text = ex.Message;
    }

    finally
    {
        sqlConnection.Close();
    }
  }
}

我想捕获最后一个user_id,它被定义为自动增量的标识。

这是我得到的错误

  

发生了'System.IndexOutOfRangeException'类型的异常   System.Data.dll但未在用户代码中处理。

     

附加信息:带有ParameterName'@ id_user'的SqlParameter   不包含在此SqlParameterCollection中。

我决定拆分这两个请求。 1个插入和1个选择

    SqlConnection sqlConnection;
    sqlConnection = new SqlConnection();

    try
    {
        sqlConnection.ConnectionString = sqlDataSource1.ConnectionString;

        string insertStatement = "INSERT INTO [User] "
                                 + "(email, hash, salt, name) "
                                 + "VALUES (@email, @hash, @salt, @name)";

        SqlCommand insertCommand = new SqlCommand(insertStatement, sqlConnection);

        insertCommand.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = sEmail;
        insertCommand.Parameters.Add("@hash", SqlDbType.VarChar, 50).Value = passwordHash;
        insertCommand.Parameters.Add("@salt", SqlDbType.VarChar, 50).Value = salt;
        insertCommand.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = sName;

        sqlConnection.Open();

        int count = insertCommand.ExecuteNonQuery();

        insertCommand.Dispose();

        if (count >= 1)
        {
            string selectStatement = "SELECT SCOPE_IDENTITY() AS id_user";
            SqlCommand selectCommand = new SqlCommand(selectStatement, sqlConnection);
            selectCommand.Parameters.Add("@Id_user", SqlDbType.Int, 0, "Id_user");
            int newID = (int)selectCommand.ExecuteScalar();

            int User_ID = Convert.ToInt32(selectCommand.Parameters["@Id_user"].Value);
            Session["Id_user"] = User_ID;

            buserIdAuthenticated = true;                   
            Session["userIdAuthenticated"] = buserIdAuthenticated;
            Response.Redirect("../pages/Bienvenue.aspx");
        }
    }

    catch (SqlException ex)
    {
        lblMessage.Text = ex.Message;
    }

    finally
    {
        sqlConnection.Close();
    }
  }
 }

2 个答案:

答案 0 :(得分:1)

您不应该在两个查询中拆分查询。您应该在插入查询中选择/设置结果。

我为你做了一个例子:

第一种方法是使用select

返回单个值
private void Method1()
{
    string sEmail = "test@test.com";
    string passwordHash = "#$@#$@!#@$$@#!#@$!#@$!";
    string salt = "????";
    string sName = "John";

    using (SqlConnection sqlConnection = new SqlConnection(_connectionString))
        try
        {
            sqlConnection.Open();

            string insertStatement = "INSERT INTO [User] "
                                        + "(email, hash, salt, name) "
                                        + "VALUES (@email, @hash, @salt, @name)"

                                        + "SELECT SCOPE_IDENTITY()";

            using (SqlCommand insertCommand = new SqlCommand(insertStatement, sqlConnection))
            {

                insertCommand.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = sEmail;
                insertCommand.Parameters.Add("@hash", SqlDbType.VarChar, 50).Value = passwordHash;
                insertCommand.Parameters.Add("@salt", SqlDbType.VarChar, 50).Value = salt;
                insertCommand.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = sName;


                int userId = Convert.ToInt32(insertCommand.ExecuteScalar());
                Trace.WriteLine("User created with id: " + userId);
            }
        }

        catch (SqlException ex)
        {
            Trace.WriteLine(ex.Message);
            //lblMessage.Text = ex.Message;
        }
}

第二种方法是定义输出参数,这样就可以返回多个值。

private void Method2()
{
    string sEmail = "test@test.com";
    string passwordHash = "#$@#$@!#@$$@#!#@$!#@$!";
    string salt = "????";
    string sName = "John";

    using (SqlConnection sqlConnection = new SqlConnection(_connectionString))
        try
        {
            sqlConnection.Open();

            string insertStatement = "INSERT INTO [User] "
                                        + "(email, hash, salt, name) "
                                        + "VALUES (@email, @hash, @salt, @name)"

                                        + "SET @user_id = SCOPE_IDENTITY()";

            using (SqlCommand insertCommand = new SqlCommand(insertStatement, sqlConnection))
            {

                insertCommand.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = sEmail;
                insertCommand.Parameters.Add("@hash", SqlDbType.VarChar, 50).Value = passwordHash;
                insertCommand.Parameters.Add("@salt", SqlDbType.VarChar, 50).Value = salt;
                insertCommand.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = sName;

                insertCommand.Parameters.Add("@user_id", SqlDbType.Int).Direction = ParameterDirection.Output;

                insertCommand.ExecuteNonQuery();

                int userId = Convert.ToInt32(insertCommand.Parameters["@user_id"].Value);
                Trace.WriteLine("User created with id: " + userId);
            }
        }

        catch (SqlException ex)
        {
            Trace.WriteLine(ex.Message);
            //lblMessage.Text = ex.Message;
        }
}

如果查询是静态的,您可以做的最好的事情就是将这些查询放在存储过程中。这将加快查询速度。

答案 1 :(得分:0)

如评论中所述:

string insertStatement = "INSERT INTO [User] "
                                 + "(email, hash, salt, name) "
                                 + "VALUES (@email, @hash, @salt, @name);"
                                 + "SELECT @id_user = SCOPE_IDENTIY();";

应该是:

string insertStatement = "INSERT INTO [User] "
                                 + "(email, hash, salt, name) "
                                 + "VALUES (@email, @hash, @salt, @name);"
                                 + "SELECT SCOPE_IDENTITY() AS id_user;";

查看SCOPE_IDENTIYSCOPE_IDENTITY之间的区别。

并注意SELECT语句语法的更新。