Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : autoincrement fields separately

Tags:

sql-server

I have a table with two columns, where none of the columns is unique. I need to auto increment the column number separately for each user.

user | number
1    | 1
2    | 1
1    | 2 
3    | 1

The only idea I could come up with is to search for the last number used and manually increment by one. Is there a more efficient way?

like image 307
nsamsonau Avatar asked Sep 03 '26 00:09

nsamsonau


1 Answers

Instead of the number field, You can create an auto increment field in the table (I call it id), and get the desired number via a query:

first adding id:

alter table table_name add id int not null IDENTITY(1,1)

you do not need the number field anymore:

alter table table_name drop column number

The query to get number (you can use it to create a view):

select user,
row_number() over(partition by user order by id) as number
from table_name
like image 111
Ormoz Avatar answered Sep 05 '26 16:09

Ormoz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!