简体   繁体   中英

How can I update all rows in a table and increment a column?

I have a table in a SQL Server 2008 database. I need to update a particular column's value but increment it's value at the same time. To explain:

If the table is :

CREATE TABLE [dbo].[Player]
(
    [PlayerID] [uniqueidentifier] NOT NULL,
    [UnitID] [uniqueidentifier] NULL,
    [ExerciseID] [uniqueidentifier] NOT NULL,
    [Designation] [nvarchar](256) NOT NULL
)

I want to go through every row which has an ExerciseID of 42C45D73-3FE6-4AFA-8E2F-09BDFC6CBDF7 and update the Designation to be Player - X but X should start at 1 and increment itself by one every time.

So the first player to be updated would be Player - 1 the second would be Player - 2 and so on.

I have no idea where to start with something like this!

Thanks

; with numbering as (
  select PlayerID,
         UnitID,
         ExerciseID,
         Designation,
         row_number () over (order by PlayerID) - 1 rn
    from Player
   where ExerciseID = '42C45D73-3FE6-4AFA-8E2F-09BDFC6CBDF7'
)
update numbering
   set Designation = 'Player - ' + convert(varchar(10), rn)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM