简体   繁体   中英

Change a natural key to surrogate key

I have two tables, one witch primary key is a natural one and another who reference the first one (so referencing the natural key). Now I have to do some change over that part of my system and to start with I want to replace the natural key with a surrogate key (witch will simplify thing along the way).

I have most of my migration script written but I can't figure out how to populate the new reference column.

Let me illustrate what I mean with an exemple.

naturalKeyedTable
(
    newPk UNIQUEIDENTIFIER
    myOldPk VARCHAR(10)
    --other unimportant columns
)

referenceTable
(
    newFK UNIQUEIDENTIFIER
    oldFK VARCHAR(10)
)

I have populated the newPk column with the following SQL

UPDATE naturalKeyedTable
SET newPk = NEWID()

Now I need to also populate the newFK column. I can't quite figure out the required sql to do so.

I have tought something along the line of

UPDATE referenceTable
SET newFK = SELECT TOP 1 newPk FROM naturalKeyedTable WHERE oldFK = myOldPk 

Something more like this.

update rt
set newFK = newPK
from referenceTable rt
join naturalKeyedTable nkt on nkt.myOldPk = rt.oldFK

Do be careful here. Your new primary key is a guid. I hope you have another column you can use as your clustered key. GUID columns as the clustered index will hit 99% fragmentation with as few as a few thousand rows and unless you defragment this index regularly your performance will be horrible.

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