Sql 获取select语句将获取的行数(无实际获取)
假设我有许多sql语句,如下所示:Sql 获取select语句将获取的行数(无实际获取),sql,sql-server-2008,Sql,Sql Server 2008,假设我有许多sql语句,如下所示: select * from [A] where a in ( select a from [B] where b = 'c' ) order by d; 因为我的数据库很大,所以我只需要确定这个查询将获取多少行。当然,我真的可以获取所有行并进行计数,但我的目的是避免获取,因为这将是一个巨大的开销 我已尝试按如下方式扩展查询: select count
select *
from [A]
where a in (
select a
from [B]
where b = 'c'
)
order by d;
因为我的数据库很大,所以我只需要确定这个查询将获取多少行。当然,我真的可以获取所有行并进行计数,但我的目的是避免获取,因为这将是一个巨大的开销
我已尝试按如下方式扩展查询:
select count (*)
from (
select *
from [A]
where a in (
select a
from [B]
where b = 'c'
)
order by d
) as table;
这对于某些表很好,但对于某些表(如示例中的此表),SQL server会抛出以下命令:
除非还指定了TOP或FOR XML,否则ORDER BY子句在视图、内联函数、派生表、子查询和公共表表达式中无效
考虑到我不允许更改任何原始查询,我可以扩展它 有什么想法吗? 谢谢
编辑:我很确定有一些与@ROWCOUNT字段相关的解决方案,但不确定如何使用它…只需删除子查询中的
order by
。它不影响行数:
select count(*)
from (select *
from [A]
where a in (select a from [B] where b = 'c')
) as table;
实际上,这最好写为:
select count(*)
from [A]
where a in (select a from [B] where b = 'c')
也就是说,只需将select*
替换为select count(*)
最后,如果必须保持查询不变,请使用top 100%
:
select count(*)
from (select top 100 percent *
from [A]
where a in (select a from [B] where b = 'c')
order by d
) as table;
这确实需要更改原始查询,但不影响它们的输出,并且允许它们用作CTE/子查询
当您同时使用top
时,可以在子查询中使用order by
编辑:
如果您使用的是动态SQL,则可能需要执行以下操作:
@sql = 'select count(*) from (' +
(case when @sql not like 'SELECT TOP %'
then stuff(@sql, 1, 7, 'SELECT top 100 percent')
else @sql
end) +
+ ')';
如果SQL格式不好,逻辑可能会更复杂。真正的问题是需求。捡东西,边捡边数。在获取之前计数是一种资源浪费,服务器必须做两次这项工作。没有理由。仅仅通过添加周围的语法,不可能将类似于
SELECT*fromtorderbyc
的查询转换为计数查询。您可以做的一件事是查看它的估计执行计划,并查看估计的行数。可能并不准确,“我不允许更改任何原始查询,我可以扩展它”@MartinSmith。现在的答案解决了这个问题。我对“扩展”查询的确切含义有点模糊。谢谢大家,但马丁是对的。原始查询必须保持不变。