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?
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.
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).
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.
@@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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With