Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number Of Records Affected With This Statement

How can I get the number of records affected by this statement:

select * from x_table where column1 = 5

I thought ExecuteNonQuery is what I need but it returned -1. I expected 2 because I have two records with column1 = 5 in my table. How do I get the correct count?

like image 324
Arash Avatar asked Sep 06 '11 19:09

Arash


People also ask

How can I get the number of records affected by a stored procedure?

Register an out parameter for the stored procedure, and set the value based on @@ROWCOUNT if using SQL Server. Use SQL%ROWCOUNT if you are using Oracle. Mind that if you have multiple INSERT/UPDATE/DELETE , you'll need a variable to store the result from @@ROWCOUNT for each operation. Save this answer.

How do you count the number of records?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How can you know the number of rows affected by last SQL statement?

Usage. SQL Server @@ROWCOUNT is a system variable that is used to return the number of rows that are affected by the last executed statement in the batch.

How do I count the number of rows affected?

@@ROWCOUNT – Get the Number of Rows Affected by the Last Statement in SQL Server. In SQL Server, you can use the @@ROWCOUNT system function to return the number of rows affected by the last T-SQL statement. For example, if a query returns 4 rows, @@ROWCOUNT will return 4.


1 Answers

You're calling ExecuteNonQuery - but this is a query! No rows are affected by your statement because it's just a query. You need to put the counting part into the query, like this:

select count(*) from x_table where column1 = 5

And then the simplest way of getting the result is to use ExecuteScalar:

int count = (int) command.ExecuteScalar();

You could just execute it as a reader and get the sole result, but ExecuteScalar is simpler.

like image 179
Jon Skeet Avatar answered Sep 24 '22 19:09

Jon Skeet