且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 SELECT T-SQL 命令的结果集中包含返回的总行数?

更新时间:2022-10-14 21:12:41

在 SQL Server 2008 及更高版本中,添加 COUNT(*) OVER() 作为其中之一查询中的列名称,并将填充返回的总行数.

它在每一行中重复,但至少值是可用的.

许多其他解决方案不起作用的原因是,对于非常大的结果集,直到迭代所有行之后您才会知道总数,这在许多情况下是不切实际的(尤其是顺序处理解决方案).例如,此技术可在调用第一个 IDataReader.Read() 后为您提供总计数.

select COUNT(*) OVER() as Total_Rows, ... from ...

I would like to ask if there is a way to include the total number of rows, as an additional column, in the returned result sets from a TSQL query using also the Row_Number command.

For example, getting the results set from a query against Book table in a form similar to this:

RowNum   BookId     BookTitle    TotalRows
--------------------------------------------
1        1056       Title1       5    
2        1467       Title2       5    
3        121        Title3       5    
4        1789       Title4       5    
5        789        Title5       5

The query is part of custom paging functionality implemented in a stored procedure. The goal is to return back only the records for the current page Index and limited to the page size, but also the amount of total number of records in the select statement in order to determine the total number of resultset pages.

In SQL Server 2008 and later, add COUNT(*) OVER () as one of the column names in your query and that will be populated with the total rows returned.

It is repeated in every single row but at least the value is available.

The reason why many other solutions do not work is that, for very large result sets, you will not know the total until after iterating all rows which is not practical in many cases (especially sequential processing solutions). This technique gives you the total count after calling the first IDataReader.Read(), for instance.

select COUNT(*) OVER () as Total_Rows, ... from ...