INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

T-SQL Hints and Tips

How Do I Get a Row Number On Each Row of a Query Result Set? by tlbroadbent
Posted: 12 Jan 03


It is often desirable to have a row number on each row of a query result set. Unfortunately, T-SQL doesn't provide RowNum like you will find in Oracle. Here are a couple of methods for adding a row number column.

For small tables use a sub-query to count the rows up to and including the current row. An assumption is made that there is a primary key or unique index on the table.

--Assume the primary key is a composite of Col1 and Col2.
Select
 RowNum=(Select Count(*) From TableName
         Where Col1<=t1.Col1 And Col2 <=t1.Col2)
 Col1, Col2, Col3, Col4
From TableName t1
Order By Col1, Col2

For larger tables it is usually faster to insert the rows selected into a temp table with an identity column, and then select from the temp table.

Create table #temp
 (Col1 varchar(10),
  Col2 varchar(10),
  Col3 Int,
  Col4 Decimal(12,2),
  RowNum Int Identity)

Insert #temp(Col1, Col2, Col3, Col4)
Select Col1, Col2, Col3, Col4 From TableName
Order By Col1, Col2

Select RowNum, Col1, Col2, Col3, Col4
From #temp
Order By RowNum

Neither of these methods is very efficient but will provide a row number when needed. If you have another method that you prefer to use, please let me know. Any other comments or recommendations are welcome.

Back to Microsoft SQL Server: Programming FAQ Index
Back to Microsoft SQL Server: Programming Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close