How to include the total number of returned rows in the resultset from SELECT T-SQL command?

前端 未结 7 1539
一整个雨季
一整个雨季 2020-12-09 09:29

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_Nu

7条回答
  •  Happy的楠姐
    2020-12-09 09:48

    Via comments attached to the question it's clear that this question relates to paging. In that scenario, there are two broad approaches:

    1. Query all rows that match the search criteria (not just one page worth) and store into a table valued variable (along with a ROW_NUMBER). Then run two queries against that table valued variable: one to extract the desired page of data and the second to to get the total count.
    2. Don't use a table-valued variable and just run the full query twice, once to get the page of data and once for the total count.

    The first option works well if the total number of rows is measured in the thousands. If the total number is much higher, you best bet is to run the query twice.

    This is a typical space/processing trade-off.

    Your milage may vary - what works well for one situation may be terrible in another!

提交回复
热议问题