Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - Auto Increment in an UPDATE statement

SQL Server 2005

I have a table containing the following: -

[order_id]     [index_1]
600020001      0
600020002      0
600020002      0
600020002      0
600020003      0
...

which needs to be updated to: -

[order_id]     [index_1]
600020001      1
600020002      1
600020002      2
600020002      3
600020003      1  

I am trying to write an UPDATE statement that will populate the index_1 field, as per the example above. I can acheive this using a CURSOR, but ideally would like to do it without if possible.

For each new order_id the numbering restarts. For each order_id row the index_1 field is incremented by 1.

Is it possible to do this without a cursor?

like image 266
Andy B Avatar asked Aug 05 '11 13:08

Andy B


People also ask

What is the syntax for auto increment in SQL Server?

Syntax for SQL Server. The following SQL statement defines the "Personid" column to be an auto-increment primary key field in the "Persons" table: ); 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.

How do I set auto increment in MySQL?

MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement: ALTER TABLE Persons AUTO_INCREMENT=100;

How do I create an auto-increment primary key field in SQL?

The following SQL statement defines the "Personid" column to be an auto-increment primary key field in the "Persons" table: ); 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.

How to let auto_increment sequence start with another value?

By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:


1 Answers

You can use a CTE and row_number() to do what you want. The table @T in the code below is only for demonstration. Replace @T with whatever your table is called.

declare @T table ([order_id] int, [index_1] int)

insert into @T values
(600020001,      0),
(600020002,      0),
(600020002,      0),
(600020002,      0),
(600020003,      0)

;with cte as
(
  select index_1,
         row_number() over(partition by order_id order by (select 1)) as rn
  from @T       
)
update cte 
  set index_1 = rn

select *
from @T

Result:

order_id    index_1
----------- -----------
600020001   1
600020002   1
600020002   2
600020002   3
600020003   1
like image 161
Mikael Eriksson Avatar answered Sep 26 '22 02:09

Mikael Eriksson