views:

273

answers:

1

I've got a SQL statement in SQL Server 2005 that looks something like this:

SELECT * INTO #TempTable FROM FirstTable WHERE <complex where clause>

What I would really, really like is to have the resulting temp table have an extra field that is essentially an integer field counting from 1 up in the order the where clause returned the records.

Is this possible?

(Essentially, I want to be able to return a subset of the records returned from the first select statement, along the lines of "lines 45 through 179".)

+4  A: 

Try this, using Row_Number:

-- insert into temp table
SELECT *, 
  ROW_NUMBER() OVER (ORDER BY SortColumn) AS SortColumn INTO #TempTable 
FROM FirstTable 
WHERE <complex where clause>

-- check the results and drop the table
SELECT * FROM #TempTable WHERE SortColumn BETWEEN 45 AND 179 ORDER BY SortColumn
DROP TABLE  #TempTable

Obviously you'll need to replace SortColumn with whatever makes sense in your case


Edit:

If you're just trying to do paging, there are lots of examples of that:

Michael Haren
I'd add an ORDER BY SortColumn to the end of the first statement as well, just in case.
Joel Coehoorn
Good point Joel. I updated it with an order by on the temp table select and added in the window criteria.
Michael Haren
@Electrons_Ahoy: if you really only need a subset of the records, checkout the paging links I included--there are lots of ways to do this more efficiently without temp tables.
Michael Haren
Well, that's just perfect. I am doing paging, but (as usual) I'm just modifying an existing ginormous stored procedure, so I've inherited the temp table and associated logic. :) Those links are fantasic, though. Thanks a bundle.
Electrons_Ahoy