Aquí hay una muestra de cómo puede hacerlo usando ON UPDATE CASCADE
opción de clave externa. La parte que le interesará son los dos ALTER TABLE
declaraciones.
Si está utilizando IDENTITY
columnas para sus claves principales, entonces esto se vuelve más difícil ya que no puede actualizar una IDENTITY
columna.
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