Her er et eksempel på, hvordan du kan gøre det ved hjælp af ON UPDATE CASCADE
mulighed for fremmednøgle. Den del, du vil være interesseret i, er de to ALTER TABLE
udsagn.
Hvis du bruger IDENTITY
kolonner for dine primære nøgler, så bliver dette sværere, da du ikke kan opdatere en IDENTITY
kolonne.
CREATE TABLE Parent
(
ParentId INT NOT NULL CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED,
Name VARCHAR(10) NOT NULL
)
CREATE TABLE Child
(
ChildId INT NOT NULL CONSTRAINT [PK_Child] PRIMARY KEY CLUSTERED,
ParentId INT NOT NULL CONSTRAINT [FK_Child_ParentId] FOREIGN KEY REFERENCES Parent (ParentId),
Name VARCHAR(10) NOT NULL
)
INSERT INTO Parent (ParentId, Name) VALUES (1, 'Bob')
INSERT INTO Parent (ParentId, Name) VALUES (2, 'Sue')
INSERT INTO Child (ChildId, Name, ParentId) VALUES (1, 'Alice', 1)
INSERT INTO Child (ChildId, Name, ParentId) VALUES (2, 'Billy', 2)
SELECT * FROM Child
-- Drop foreign key constraint and re-add
ALTER TABLE Child
DROP CONSTRAINT [FK_Child_ParentId]
ALTER TABLE Child
ADD CONSTRAINT [FK_Child_ParentId]
FOREIGN KEY (ParentId) REFERENCES Parent (ParentId) ON UPDATE CASCADE
UPDATE Parent SET ParentId = ParentId + 100
SELECT * FROM Child --shows the new ParentIds
DROP TABLE Child
DROP TABLE Parent