I have the following two tables and data:-
CREATE TABLE customers
([id] int, [name] varchar(10), [sex] varchar(1))
;
INSERT INTO customers
([id], [name], [sex])
VALUES
(1050, 'John Doe', 'M'),
(1060, 'Jane Doe', 'F'),
(1031, 'Joe Bloggs', 'M')
;
CREATE TABLE orders
([id] int, [fk] int, [product] varchar(13))
;
INSERT INTO orders
([id], [fk], [product])
VALUES
(51, 1050, 'Blue car'),
(57, 1050, 'Yellow car'),
(43, 1060, 'Pink bus'),
(32, 1031, 'Black pen'),
(87, 1031, 'Orange jacket')
;
What i want to do is re-number the id column in both tables sequentially starting from 1.
The linked rows in the orders table must also be renumbered, and the foreign key in this table must match the new number in the customers table.
so the data needs to end up looking like this:-
ID NAME SEX
0001 John Doe M
0002 Jane Doe F
0003 Joe Bloggs M
ID FK PRODUCT
0001 0001 Blue car
0002 0001 Yellow car
0003 0002 Pink bus
0004 0003 Black pen
0005 0003 Orange jacket
How would I go about doing this in SQL Server ?
Absolutely no need to resort to cursor (yikes!) here…. you need something like this:
That’ll work, if you don’t have any other FK relationships that are referencing one of those two tables. If you do, then you might need to disable or drop those FK relationships before you start this upgrade script.