简体   繁体   中英

retrieve updated parameter value on asp.net with sqlcommand

I'm using a query to update a column value on table and also retrieve the updated value using the following way on the ASP.NET site. Is there any way to use single query instead of double queries as below?

using (SqlConnection connection = new SqlConnection(connStr)){
    string updateUserQuery = "Update user_master set login_failed_attempts = login_failed_attempts + 1  where id = @id; Select @login_failed = login_failed_attempts from user_master where id = @id";
    SqlCommand cmd = new SqlCommand(updateUserQuery, connection);
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = user_id;
    SqlParameter outputIdParam = new SqlParameter("@login_failed", SqlDbType.Int)
    {
        Direction = ParameterDirection.Output
    };
    cmd.Parameters.Add(outputIdParam);
    cmd.ExecuteNonQuery();
    int loginFailedAttempts = int.Parse(outputIdParam.Value.ToString());
}

Updated code is given below after Matthew's answer.

string updateUserQuery = "Update user_master set login_failed_attempts = login_failed_attempts + 1 OUTPUT INSERTED.login_failed_attempts where id = @id";
SqlCommand cmd = new SqlCommand(updateUserQuery, connection);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = user_id;
int loginFailedAttempts = (int)cmd.ExecuteScalar();

Use an OUTPUT clause.

UPDATE user_master
SET login_failed_attempts = login_failed_attempts + 1
OUTPUT INSERTED.login_failed_attempts
WHERE id = @id

Then change your ExecuteNonQuery to an ExecuteScalar and use the result from that accordingly.

You could also change it to an ExecuteReader and pull back multiple records, but given your use of @id I'm assuming you don't want that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM