TSQL: How to update each record with forreign key -
i have old table in ms sql not has primary key. structure is:
- document
- position
- material
- quantity
- ..
i want change that, , put "document" , "position" keys of table. of course each combination should unique. new records done old 1 "position" field missing.
what want update of existing record position null incrementational number (each time change document change, counter should start again @ 1)
what should tsql sentence in order quickly?
thank youit
you can use cte
, ranking function row_number
:
with cte as( select document, position, material, quantity, rn = row_number() on (partition document order document asc) dbo.tablename ) update cte set position = rn position null
if need specific logic order change order document asc
meaningful.
if want see updated have change update select * cte position null
. that's 1 of benefits of common-table-expression(cte).
Comments
Post a Comment