how to know how many rows will be affected before running a query in microsoft sql server 2008

10,558

Solution 1

Short answer is no..

You cannot get the number of rows before executing the query..atleast in SQL server.

The best way to do it is use

Select count(*) from <table> where <condtion>

then execute your actual query

 [delete]or [update] [set col='val']
 from <table> where <condtion>

Solution 2

You can also use BEGIN TRANSACTION before the operation is executed. You can see the number of rows affected. From there, either COMMIT the results or use ROLLBACK to put the data back in the original state.

BEGIN TRANSACTION;

UPDATE table
SET col = 'something'
WHERE col2 = 'something else';

Review changed data and then:

COMMIT;

or

ROLLBACK;

Solution 3

The estimated execution plan is going to give you rows affected based on statistics, so it won't really help you in this case.

What I would recommend is copying your UPDATE statement or DELETE statement and turning it into a SELECT. Run that to see how many rows come back and you have your answer to how many rows would have been updated or deleted.

Eg:

UPDATE t
SET t.Value = 'Something'
FROM MyTable t
WHERE t.OtherValue = 'Something Else'

becomes:

SELECT COUNT(*)
FROM MyTable t
WHERE t.OtherValue = 'Something Else'

Solution 4

Simplest solution is to replace the columns in the SELECT * FROM... with SELECT Count(*) FROM ... and the rest of your query(the WHERE clause needs to be the same) before you run it. This will tell you how many rows will be affected

Share:
10,558
user571099
Author by

user571099

Updated on June 07, 2022

Comments

  • user571099
    user571099 about 2 years

    i've read a bit about ROWCOUNT but its not exactly what im looking for. from my understanding rowcount states the number of rows affected AFTER you run the query. what im looking for is knowing BEFORE you run the query. is this possible?

  • rvphx
    rvphx over 9 years
    Although you can use the SQL Server Analytical functions to get the total number of rows that are getting effected. But this is at Runtime only.
  • Himanshu Saini
    Himanshu Saini about 9 years
    will not be always correct as update will skip rows where nothing to need to be change. for example: new value and old value is already same.
  • Joe G Joseph
    Joe G Joseph almost 9 years
    @HimanshuSaini : As far I know, SQL server will not check whether the old and new values are same, before updating. It Just updates all the records with matching conditions. Please share if you have any documents regarding that. That would be new learning for me
  • user890332
    user890332 almost 5 years
    This is the better answer when you cant use a select because your doing an update from select (...