使用sqlcommand检索asp.net上更新的参数值

本文关键字:更新 参数 net sqlcommand 检索 asp 使用 | 更新日期: 2023-09-27 18:14:31

我使用查询来更新表上的列值,并在ASP上使用以下方式检索更新的值。网的网站。是否有办法使用单一查询,而不是双重查询如下?

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());
}

在Matthew的回答之后给出了更新的代码。

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();

使用sqlcommand检索asp.net上更新的参数值

使用OUTPUT子句

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

然后将ExecuteNonQuery更改为ExecuteScalar并使用相应的结果。

您也可以将其更改为ExecuteReader并拉回多个记录,但考虑到您使用@id,我假设您不希望这样做。