Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SERVER, SELECT statement with auto generate row id

Tags:

sql-server

Does anyone happen to remember the function name used to generate sequential row number built-in SQL Server 2000.

like image 409
c.sokun Avatar asked Sep 26 '08 04:09

c.sokun


People also ask

How do I generate a row ID?

Row IDs are generated by the grid when data is supplied to the grid. The grid uses a sequence starting at 0 and incrementing by 1 to assign row IDs, so for example if there are three rows they will have IDs of 0 , 1 and 2 . The row ID does not change for a row once it is set.

How do I increment a SQL select statement?

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) .


2 Answers

If you are making use of GUIDs this should be nice and easy, if you are looking for an integer ID, you will have to wait for another answer.

SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1

The newId() will generate a new GUID for you that you can use as your automatically generated id column.

like image 157
FryHard Avatar answered Sep 27 '22 16:09

FryHard


Here is a simple method which ranks the rows after however they are ordered, i.e. inserted in your table. In your SELECT statement simply add the field

ROW_NUMBER() OVER (ORDER BY CAST(GETDATE() AS TIMESTAMP)) AS RowNumber.
like image 43
Martin Widlund Avatar answered Sep 27 '22 17:09

Martin Widlund