简体   繁体   English

在microsoft sql server 2008中运行查询之前如何知道将影响多少行

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

i've read a bit about ROWCOUNT but its not exactly what im looking for. 我读过一些关于ROWCOUNT的内容,但它并不是我想要的。 from my understanding rowcount states the number of rows affected AFTER you run the query. 从我的理解rowcount说明运行查询后受影响的行数。 what im looking for is knowing BEFORE you run the query. 我正在寻找的是在运行查询之前知道。 is this possible? 这可能吗?

Short answer is no.. 简短的回答是没有..

You cannot get the number of rows before executing the query..atleast in SQL server. 在SQL Server中执行query..atleast之前,无法获取行数。

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>

You can also use BEGIN TRANSACTION before the operation is executed. 您也可以在执行操作之前使用BEGIN TRANSACTION 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. 从那里, COMMIT结果或使用ROLLBACK将数据恢复到原始状态。

BEGIN TRANSACTION;

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

Review changed data and then: 查看已更改的数据,然后:

COMMIT;

or 要么

ROLLBACK;

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 . 我建议复制UPDATE statementDELETE statement并将其转换为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'

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. 最简单的解决方案是在运行之前用SELECT Count(*) FROM ...替换SELECT * FROM...的列,并将其余查询( WHERE子句必须相同)替换。 This will tell you how many rows will be affected 这将告诉您将受影响的行数

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 在这里,我认为你需要BEGIN TRANSACTION

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM