C# 使用sqlcommand在asp.net上检索更新的参数值
我正在使用查询更新表中的列值,并在ASP.NET站点上使用以下方法检索更新后的值。有没有办法使用单查询而不是下面的双查询C# 使用sqlcommand在asp.net上检索更新的参数值,c#,asp.net,sql-server,sqlcommand,C#,Asp.net,Sql Server,Sqlcommand,我正在使用查询更新表中的列值,并在ASP.NET站点上使用以下方法检索更新后的值。有没有办法使用单查询而不是下面的双查询 using (SqlConnection connection = new SqlConnection(connStr)){ string updateUserQuery = "Update user_master set login_failed_attempts = login_failed_attempts + 1 where id = @id; Select
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();
使用子句
然后将ExecuteNonQuery
更改为,并相应地使用该查询的结果
您也可以将其更改为
ExecuteReader
,并调回多条记录,但鉴于您使用了@id
,我假设您不希望这样做。这就是我要找的。谢谢
UPDATE user_master
SET login_failed_attempts = login_failed_attempts + 1
OUTPUT INSERTED.login_failed_attempts
WHERE id = @id