让我们说,我有许多类似于此的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 server会抛出以下内容:
ORDER子句在视图、内联函数、派生表、子查询和公共表表达式中无效,除非还指定了TOP或FOR XML。
考虑到我不允许更改任何原始查询,我可以扩展它.
有什么想法吗?谢谢。
编辑:我很确定有一些与@@ROWCOUNT字段相关的解决方案,但不确定如何使用它.
发布于 2014-02-05 12:52:44
只需删除子查询中的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没有很好的格式化,那么逻辑可能会更复杂一些。
https://stackoverflow.com/questions/21577825
复制相似问题