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

mainrotor
mainrotor used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Shaun KlineLead Software Engineer

Commented:
Take a look at the ROW_NUMBER() function:
https://msdn.microsoft.com/en-us/library/ms186734.aspx
Andrew CalhounSystems Engineer

Commented:
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);
IT Engineer
Distinguished Expert 2017
Commented:
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

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial