Adam Ricketts
Adam Ricketts

Reputation: 23

SQL Table Row Number Column?

I am writing a program in SQL, but every time I execute the program in MSSMS, there is a column on the far left that contains row numbers. I would like to call the the row numbers in this column in a while statement I am using in the same program, but I'm not sure how to refer to it in the code. What is this column called so that I can call it and get the row numbers?

Upvotes: 1

Views: 1972

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522817

The column to which you are referring is generated by SQL Server and does not actually exist in your result set. If there exists one or more columns in your table which would generate that ordering, then you may add a call to ROW_NUMBER to obtain that column you are seeing. For example:

SELECT *, ROW_NUMBER() OVER (ORDER BY some_col) rn
FROM yourTable
ORDER BY rn;

Upvotes: 3

Gordon Linoff
Gordon Linoff

Reputation: 1271231

You can add your own row numbers using row_number():

select row_number() over (order by <order cols>) as seqnum,
       . . .
from t
order by <order cols>;

These are in the data and can be referenced in subsequent processing.

Upvotes: 0

Related Questions