Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSSQL Select statement with incremental integer column... not from a table

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

like image 700
Rodrigo Avatar asked Feb 10 '09 21:02

Rodrigo


People also ask

Can I use select statement without from?

To select values from SQL expressions, a FROM clause is not strictly required as the expression is not selected from that table anyway.

How do you auto increment a column value in SQL?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

How do you create a sequence number in a select query?

The Rank function can be used to generate a sequential number for each row or to give a rank based on specific criteria. The ranking function returns a ranking value for each row. However, based on criteria more than one row can get the same rank.

Can you select a column by number in SQL?

You can only refer to columns by column number in the ORDER BY clause or using the positional notation when using the DBMS_SQL package to execute the statement. (or if you're using . NET or some other 3rd party language that uses positional notation). In a regular SQL statement you can't use such notation.


3 Answers

For SQL 2005 and up

SELECT ROW_NUMBER() OVER( ORDER BY SomeColumn ) AS 'rownumber',*
    FROM YourTable

for 2000 you need to do something like this

SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
INTO #Ranks FROM YourTable WHERE 1=0

INSERT INTO #Ranks
SELECT SomeColumn  FROM YourTable
ORDER BY SomeColumn 

SELECT * FROM #Ranks
Order By Ranks

see also here Row Number

like image 123
SQLMenace Avatar answered Sep 23 '22 06:09

SQLMenace


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:

select @StartChequeNumber = 3446;
SELECT 
((ROW_NUMBER() OVER(ORDER BY AnyColumn)) + @StartChequeNumber ) AS 'ChequeNumber'
,* FROM YourTable

will give the correct cheque number for each row.

like image 32
Israel Margulies Avatar answered Sep 21 '22 06:09

Israel Margulies


Try ROW_NUMBER()

http://msdn.microsoft.com/en-us/library/ms186734.aspx

Example:

SELECT
  col1,
  col2,
  ROW_NUMBER() OVER (ORDER BY col1) AS rownum
FROM tbl
like image 6
Misko Avatar answered Sep 22 '22 06:09

Misko