user3127554
user3127554

Reputation: 577

Check if update statement was successful

I have the following method that sets an object to a specific status (it sets a column value of a specific row to '4' :

C#

 void setObjectToFour(int objectID)
        {
            using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
            using (var command = new SqlCommand("setObjectToFour", conn)
            {
                CommandType = CommandType.StoredProcedure
            })
            {
                command.Parameters.Add(new SqlParameter("@objectID", SqlDbType.Int)).Value = objectID;
                conn.Open();
                command.ExecuteNonQuery();

            }
        }

SQL:

...
AS
BEGIN
    Update [DB_OBJECT].[dbo].[object_table]
    SET status = 4
    WHERE id = @objectID

END

The problem is that the DB_OBJECT DB is not managed by us and is the DB of a piece of software.

The followed problem is that the query from above not always works (and we haven't figured out why) and I were thinking about how we could 'force' or 'check' if the row was updated.

Is it smart to do it as follow?:

1 - Create new C# Method Check and stored procedure getStatus that retrieves the status of the object

2 - I will put both methods from above in a do while until the status is 4.

Is this a smart approach?

Upvotes: 2

Views: 4481

Answers (2)

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38663

ExecuteNonQuery() does not return data at all: only the number of rows affected by an insert, update, or delete.

try this

if (command.ExecuteNonQuery() !=  0)
{
    // more code 
}

Upvotes: 2

John Woo
John Woo

Reputation: 263683

ExecuteNonQuery() method returns the number of rows affected.

int recordAffectd = command.ExecuteNonQuery();
if (recordAffectd > 0)
{
    // do something here  
}

Upvotes: 9

Related Questions