简体   繁体   中英

How to update multiple records using data from a record in the same table in T-SQL

I need to update records in one table base on data from a certain record.

ProdFam    ProdID     Color        Form        Price    
ProdA      ProdA      White        Sheet       $100
ProdA      ProdA-10   White        Sheet       $10
ProdA      ProdA-20   White        Sheet       $15
ProdA      ProdA-25   White        Sheet       $35
ProdB      ProdB-10   Red          Roll        $24
ProdB      ProdB-15   Red          Roll        $28

So using the example above, the information for ProdA was updated by a different process and now shows that the color is Off-White and Form is Mul-Sheet.

ProdFam    ProdID     Color        Form        Price    
ProdA      ProdA      Off-White    Mul-Sheet   $100
ProdA      ProdA-10   White        Sheet       $10
ProdA      ProdA-20   White        Sheet       $15
ProdA      ProdA-25   White        Sheet       $35
ProdB      ProdB-10   Red          Roll        $24
ProdB      ProdB-15   Red          Roll        $28

I need to update the rest of the records that have the same ProdFam as ProdA to the new spec. So the end result should have ProdA all with Color of Off white and Form of Mul-Sheet but their price and ProdID to stay the same.

ProdFam    ProdID     Color        Form        Price    
ProdA      ProdA      Off-White    Mul-Sheet   $100
ProdA      ProdA-10   Off-White    Mul-Sheet   $10
ProdA      ProdA-20   Off-White    Mul-Sheet   $15
ProdA      ProdA-25   Off-White    Mul-Sheet   $35
ProdB      ProdB-10   Red          Roll        $24
ProdB      ProdB-15   Red          Roll        $28

Any help will be greatly appreciated.

Thanks

Updates affect all records determined by your WHERE clause at once and will change only the fields you specify in the UPDATE command.

For this requirement, you can self-join the table to find out the rows you must update.

update all_prod
set all_prod.Color = first_prod.Color
from MyTable as all_prod
join MyTable as first_prod on first_prod.ProdFarm = all_prod.ProdFarm
where first_prod.ProdID = 'ProdA' and first_prod.Color = 'Off-White'

Notes:

  1. and first_prod.Color = 'Off-White' is optional here, just put it to ensure it will change to the correct color.

  2. it will update the first row again unless you add another AND to prevent it.

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