How can I create a column in a SQL Server query that works as a counter

Hi Experts,
I am using a SELECT query in SQL SERVER 2008 R2.  I want to add a column to my select query that will simply provide me a running record count, incremented by 1 for each row.

How could I do this?

Thanks in advance,
mrotor
mainrotorAsked:
Who is Participating?
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
You'll need to define the column that you want the data to be sorted and numbered:
SELECT ROW_NUMBER() OVER(ORDER BY ColumnID) AS Row, 
	Column1, Column2, ..., ColumnN
FROM TableName
WHERE <YourCriteria>

Open in new window

0
 
Shaun KlineLead Software EngineerCommented:
Take a look at the ROW_NUMBER() function:
https://msdn.microsoft.com/en-us/library/ms186734.aspx
0
 
Andrew CalhounSystems EngineerCommented:
Putting a column in the table itself to keep track of rowcount doesn't make sense, if that is what you are asking for. If that is what you are asking for, imagine deleting a row from the middle of the table. Are you going to go back in and alter the value of the count column for all rows that were added after the one you just deleted, in order to keep them accurate?

Instead, any time you need the number of rows in the table, use a query like below.
replace the word tablename with the actual name of the table that you are getting the row count on (but keep the single quotes).

SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('tablename')  
AND (index_id=0 or index_id=1);
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.