简体   繁体   中英

How to update distinct column in SQL Server 2005?

In my table I have a column Segment_No which has duplicates. Now I want to update those duplicates.

表

For example: the value 249X5601 is present in two rows. I want to change the second value to 249X5601R

The general form would be as follows:

;with AllRows as (
    select Donation_ID,Registration_No,Segment_No,
           ROW_NUMBER() OVER (
               PARTITION BY Segment_No
               order by <Suitable_Column>
           ) as rn
    from UnnamedTable
)
update AllRows set Segment_no = <New_Value>
where rn > 1

Where <Suitable_Column> gives the column(s) the define which row is "first" and which is second. <New_Value> defines how the new Segment_no value should be computed, and rn gives the row numbers - so the where clause is ignoring the "first" row.

So if there are only ever a max of two rows sharing a single Segment_no value, and the "first" is the one with the lowest Donation_ID value, then it would be:

;with AllRows as (
    select Donation_ID,Registration_No,Segment_No,
           ROW_NUMBER() OVER (
               PARTITION BY Segment_No
               order by Donation_ID
           ) as rn
    from UnnamedTable
)
update AllRows set Segment_no = Segment_no + 'R'
where rn > 1

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