In SQL Server, you can use the ROW_NUMBER()
function to generate a row number for each row in your result set. Here’s a basic example:
SELECT ROW_NUMBER() OVER(ORDER BY SomeColumn) AS RowNumber, *
FROM YourTable
In this query, ROW_NUMBER() OVER(ORDER BY SomeColumn)
generates a new row number for each row, ordered by SomeColumn
. The OVER
clause determines the order in which the row numbers are assigned. You can replace SomeColumn
with the name of the column that you want to order by.
If you want to partition the row numbers by a certain column (for example, to restart the row numbers for each unique value in a certain column), you can use the PARTITION BY
clause:
SELECT ROW_NUMBER() OVER(PARTITION BY SomeColumn ORDER BY AnotherColumn) AS RowNumber, *
FROM YourTable
In this query, the row numbers restart at 1 for each unique value inĀ SomeColumn
.