how to get a count(*) for number of records updated
i am updating a sql server 2008 database using c# like this:
foreach (DataRow row in dt.Rows)
{
faxstatus = row.ItemArray[5].ToString().Contains("0000") ? "Faxed" : "Error";
query =
@"update FileLog set
FaxStatus=" + "'" + faxstatus + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1] + "'," +
"dtFaxed=" + "'" + row.ItemArray[2] + "'," +
"BiscomCode=" + "'" + row.ItemArray[5] + "', " +
"RetryCount=" + "'" + row.ItemArray[4] + "' " +
"where CONVERT(VARCHAR(255), JobID) =" + "'" + row.ItemArray[3] + "'" +
" and FaxStatus<>'Faxed'";
comman开发者_开发问答d = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
NumberOfRecordsUpdated++;
}
i would like to know whether it is possible to return how many records were updated?
Yes. Use ExecuteNonQuery
's return value. :-)
Quoting ExecuteNonQuery
's documentation:
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command.
Capture and use the result of ExecuteNonQuery
to an integer. That method returns the number of records affected by the operation.
See SqlCommand.ExecuteNonQuery Method.
That being said, how much do you trust your datasource? Enough to bet your data integrity on it? I'd be remissed if I didn't implore you to explore parameterized queries. A using
statement would also be warranted so that your disposable resources (SqlConnection
, SqlCommand
, etc.) are properly dealt with.
Append SELECT @@ROWCOUNT
to your statement and use ExecuteScalar
instead of ExecuteNoneQuery
.
Refering to SqlCommand.ExecuteNonQuery Method :
Return Value
Type: System.Int32
The number of rows affected.
You could use @@ROWCOUNT .
精彩评论