Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 generate counter for result set

Author  Topic 

KlausEngel
Yak Posting Veteran

85 Posts

Posted - 2010-12-03 : 12:12:22
I have what I believe is a simple question:
I need to write a query that returns a result set and adds a row number to each result set. How do I keep incrementing the row number?

DECLARE @row_num
SET @row_num = @row_num+1
SELECT @row_num, column1, column3
FROM MyTable

Desired result set:

1, col1Val1, col3Val1
2, col1Val2, col3Val2
3, col1Val3, co3lVal3
etc

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-12-03 : 12:22:10
Use the ROW_NUMBER() function.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2010-12-03 : 12:23:49
SELECT row_num = row_number() over (order by column1, column3), column1, column3
FROM MyTable


==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page
   

- Advertisement -