我如何知道执行更新的SQL Server存储过程是否有效?

Fra*_*sc0 2 c# sql-server stored-procedures asp.net-mvc-4

假设我有这个我无法控制的存储过程(并且无法访问第三方数据库).

我怎么知道它是否有效?

BEGIN
        Update USR
        Set usr_psswrd = @NewPassword
        where
            usr_usrnme = @UserName and usr_psswrd = @OldPassword
END
Run Code Online (Sandbox Code Playgroud)

我知道如何select在存储过程中有一个语句时读取行并读取这些行,但我不知道如何检查这个存储过程是否有效.

这就是我到目前为止所做的不起作用.存储过程有效,因为密码确实发生了变化我只是不知道在事后做了什么.

using (SqlConnection connection = new SqlConnection(connectionString))
{
            // Create the command and set its properties.
            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            command.CommandText = "USP_ChangePassword";
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add("@UserName", SqlDbType.VarChar).Value = email;
            command.Parameters.Add("@OldPassword", SqlDbType.VarChar).Value = oldPW;
            command.Parameters.Add("@NewPassword", SqlDbType.VarChar).Value = newPW;

            try
            {
                // Open the connection and execute the reader.
                connection.Open();
                command.ExecuteNonQuery();

                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    success = true;
                }

                reader.Close();

            }
            catch (SqlException ex)
            {
                System.Diagnostics.Debug.Write("SqlException Error " + ex.Number + ": " + ex.Message);
            }
            catch (InvalidOperationException ex)
            {
                System.Diagnostics.Debug.Write("Invalid Op Error: " + ex.Message);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write("Error: " + ex.Message);
            }
            finally
            {
                connection.Close();
            }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 5

在您可以找到的有关ExecuteNonQuery的文档中

> Return Value 
> Type: System.Int32 
> The number of rows affected.
Run Code Online (Sandbox Code Playgroud)

所以你可以改变你的代码

try
{
    // Open the connection and execute the reader.
    connection.Open();
    int rowsUpdated = command.ExecuteNonQuery();
    if(rowsUpdated > 0)
    {
        success = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是正常行为ExecuteNonQuery,但检查您的存储过程是否包含语句

SET NOCOUNT ON
Run Code Online (Sandbox Code Playgroud)

如果你有这一行,那么ExecuteNonQuery就不能返回受影响的行数,你总是得到-1作为返回值.如果您无法更改该存储过程,那么您就遇到了麻烦.

想到的唯一解决方法是使用SELECT查询返回用户数据并检查插入的数据(非常不舒服的情况)