I have a SQL query where I am going to be transferring a fair amount of response data down the wire, but I want to get the total rowcount as quickly as possible to facilitate binding in the UI. Basically I need to get a snapshot of all of the rows that meet a certain criteria, and then be able to page through all of the resulting rows.
Here's what I currently have:
SELECT --primary key column INTO #tempTable FROM --some table --some filter clause ORDER BY --primary key column SELECT @@ROWCOUNT SELECT --the primary key column and some others FROM #tempTable JOIN -- some table DROP TABLE #tempTable
Every once in a while, the query results end up out of order (presumably because I am doing an unordered select from the temp table).
As I see it, I have a couple of options:
- Add a second order by clause to the select from the temp table.
- Move the order by clause to the second select and let the first select be unordered.
- Create the temporary table with a primary key column to force the ordering of the temp table.
What is the best way to do this?