Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate increment number in select statement using SQL server

I have a table named table1 in SQL server as follows:

colA
-------
A123
Z123
C123
B123

now I want to use one SQL statement to get the result as follows:

ID colA
--------
1  A123
2  Z123
3  C123
4  B123

The order of colA is as the order of row in the table. Do not need to sort it.

how to do that?? Thanks a lot

like image 644
Eric Cheung Avatar asked Oct 18 '13 14:10

Eric Cheung


People also ask

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

How do I get next auto generated value in SQL?

MySQL has the AUTO_INCREMENT keyword to perform auto-increment. The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record. To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT.

Can we auto increment varchar in SQL?

No. If you really need this, you will have to generate ID manually.

What is auto increment in SQL with example?

By default, the AUTO_INCREMENT starts with 1 and increases by 1. Example: We will create Students table with fields Student_ID, First_Name, Last_Name, we will auto generate Student_ID by using auto increment and will make it Primary Key for the table.


2 Answers

Here's what I always do when I need an incrementing ID without sorting the data (because my other row or rows are neither alphabetical nor chronological). Also, I despise using temp tables unless they are absolutely necessary.

SELECT ROW_NUMBER() OVER 
(
    ORDER BY (SELECT NULL)
) as ID, colA
FROM table1
like image 143
omikes Avatar answered Nov 02 '22 23:11

omikes


Example using ROW_NUMBER

             SELECT ROW_NUMBER() 
                OVER (ORDER BY colA)  AS Row, 
                colA
                FROM table1
like image 43
PJM Avatar answered Nov 03 '22 00:11

PJM