假设我有很多像这样的sql语句:
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服务器会抛出这个:
ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOP或FOR XML。
考虑到我不允许更改任何原始查询,我可以扩展它...
有什么想法吗? 感谢。
编辑:我很确定有一些与@@ ROWCOUNT字段相关的解决方案,但不确定如何使用它...答案 0 :(得分:2)
只需删除子查询中的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 percent
:
select count(*)
from (select top 100 percent *
from [A]
where a in (select a from [B] where b = 'c')
order by d
) as table;
此 需要更改原始查询,但其方式不会影响输出内容,并允许将它们用作ctes /子查询。
当您还使用order by
时,您可以在子查询中使用top
。
编辑:
如果您使用的是动态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格式不正确,逻辑可能会有点复杂。