Generate serial numbers

I simply needed to generate serial numbers. I tried out so many options to generate it. But only with the help any other table I could achieve it.

Supposing Table1 has 10 records, below script can generate serial numbers from 1 to 10. if you want more numbers you need to select the table having sufficient records as per your requirement.
SELECT ROW_NUMBER() OVER (ORDER BY Nums) AS slno FROM Table1
If you want to generate serial numbers till 1 to 5 then you can use
SELECT TOP 5 ROW_NUMBER() OVER (ORDER BY Nums) AS slno FROM Table1

Table1
uniqid Nums
NULL data1
NULL data2
NULL data3
NULL data4
NULL data5
NULL data6
NULL data7
NULL data8
NULL data9
NULL data10

Update Serial number to an existing column.
 Assume table1 has a NULL column by name uniqid. I need to update serial numbers starting from 1. So here is the query to achieve this.
WITH cte as
(
SELECT uniqid,
ROW_NUMBER() OVER(ORDER BY (SELECT 0)) as rnk
FROM table1
)
UPDATE cte SET uniqid=rnk
If we need to update serial numbers starting from 101 then the query is
WITH cte as
(
SELECT uniqid,
ROW_NUMBER() OVER(ORDER BY (SELECT 0)) as rnk
FROM table1
)
UPDATE cte SET uniqid=100+rnk 

No comments:

Post a Comment