I need, if possible, a t-sql query that, returning the values from an arbitrary table, also returns a incremental integer column with value = 1 for the first row, 2 for the second, and so on.
This column does not actually resides in any table, and must be strictly incremental, because the ORDER BY clause could sort the rows of the table and I want the incremental row in perfect shape always...
Thanks in advance.
--EDIT Sorry, forgot to mention, must run on SQL Server 2000
Try ROW_NUMBER()
http://msdn.microsoft.com/en-us/library/ms186734.aspx
Example:
For SQL 2005 and up
for 2000 you need to do something like this
see also here Row Number
You can start with a custom number and increment from there, for example you want to add a cheque number for each payment you can do:
will give the correct cheque number for each row.
It is ugly and performs badly, but technically this works on any table with at least one unique field AND works in SQL 2000.
Note: If you use this approach and add a WHERE clause to the outer SELECT, you have to added it to the inner SELECT also if you want the numbers to be continuous.