views:

62

answers:

3

I have a numeric field (say num) in table along with pkey.

select * from mytable order by num

now how I can get the row no in query output of a particular row for which I have pkey.

I'm using sql 2000.

A: 

as i understand your question you want to get the number of all rows returned, right? if so use @@rowcount

Mladen Prajdic
+1 because you understand the question
Nicky De Maeyer
lol! yeah i've had a lot of practice with weirdly worded questions in the past :)
Mladen Prajdic
I want serial no of particular row (not of all rows) in query result.
Sharique
+2  A: 

Sounds like you want a row number for each record returned.

In SQL 2000, you can either do this:

SELECT (SELECT COUNT(*) FROM MyTable t2 WHERE t2.num <= t.num) AS RowNo, *
FROM MyTable t
ORDER BY num

which assumes num is unique. If it's not, then you'd have to use the PK field and order by that.

Or, use a temp table (or table var):

CREATE TABLE #Results
(
RowNo INTEGER IDENTITY(1,1),
MyField VARCHAR(10)
)

INSERT #Results
SELECT MyField
FROM MyTable 
ORDER BY uum

SELECT * FROM #Results

DROP TABLE #Results

In SQL 2005, there is a ROW_NUMBER() function you could use which makes life a lot easier.

AdaTheDev
first sol works if I have only 1 field, for more than 1 it doesn't.How I can work with temp tables in ado.net?
Sharique
Personally, I'd wrap the query into a stored procedure and then just call that. You could just send the query in as-is (CommandType=CommandType.Text).
AdaTheDev
A: 

As Ada points out, this task became a lot easier in SQL Server 2005....

SELECT whatever, RowNumber from (
     SELECT pk
           , whatever
          , ROW_NUMBER() OVER(ORDER BY num) AS 'RowNumber'
    FROM mytable
)
WHERE pk = 23;
APC
ROW_NUMBER() function is not available in sql 2000
Sharique