how to know how many rows will be affected before

2020-02-10 14:32发布

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?

5条回答
Anthone
2楼-- · 2020-02-10 14:59

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'
查看更多
【Aperson】
3楼-- · 2020-02-10 15:04

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>
查看更多
倾城 Initia
4楼-- · 2020-02-10 15:09

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;
查看更多
你好瞎i
5楼-- · 2020-02-10 15:15

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

查看更多
狗以群分
6楼-- · 2020-02-10 15:24

The simplest solution doesn't seem to work in a case where theres a subquery. How would you select count(*) of this update:

BEGIN TRANSACTION;
update Table1 t1 set t1.column = t2.column
from (
  SELECT column from Table2 t2
) AA
where t1.[Identity] = t2.[Identity]
COMMIT;

Here I think you need the BEGIN TRANSACTION

查看更多
登录 后发表回答