如何使用 TOP 检索查询的总行数
我有一个 SQL Server 2008 查询,
SELECT TOP 10 *
FROM T
WHERE ...
ORDER BY ...
我还想获取行的总数。 显而易见的方法是进行第二次查询
SELECT COUNT(*)
FROM T
WHERE ...
ORDER BY ...
有没有有效的方法?
谢谢
I have a SQL Server 2008 query
SELECT TOP 10 *
FROM T
WHERE ...
ORDER BY ...
I'd like to get also the total number of the rows. The obious way is to make a second query
SELECT COUNT(*)
FROM T
WHERE ...
ORDER BY ...
Is there an efficient method?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您想要第二次查询吗?
OR
或者(编辑:使用WITH)
Do you want a second query?
OR
Or (Edit: using WITH)
这个答案中的内容似乎有效:
https://stackoverflow.com/a/19125458/16241
基本上你做了一个:
TotalCount 将显示总行数。 但它列在每一行上。
当我对此进行测试时,查询计划显示该表仅被命中一次。
What is in this answer seems to work:
https://stackoverflow.com/a/19125458/16241
Basically you do a:
TotalCount will have the total number of rows. It is listed on each row though.
When I tested this the query plan showed the table only being hit once.
也从第二个查询中删除 ORDER BY 子句。
Remove the ORDER BY clause from the 2nd query as well.
不会。
SQL Server
不会像MyISAM
那样将COUNT(*)
保留在元数据中,它每次都会计算它。更新:如果您需要估计,可以使用统计元数据:
其中
@primary_key
是表的主键名称。这将返回上次统计更新的
COUNT(*)
。No.
SQL Server
doesn't keepCOUNT(*)
in metadata likeMyISAM
, it calculates it every time.UPDATE: If you need an estimate, you can use statistics metadata:
where
@primary_key
is your table's primary key name.This will return the
COUNT(*)
from last statistics update.只是想 -
使用以下参数实现存储过程:
第一次返回2个结果集。
希望这会起作用。 没有尝试过,但从逻辑上讲它会起作用。
Just thought -
Implement stored procedure with below parameters:
Return 2 result set at first time.
Hope this will work. Not tried but logically it will work.