Assume we want update the related Child tables columns after updating PK of Parent table.These tables:create table Parent(user_ID integer not null primary key, user_name char(50) not null);gocreate table Child (author_ID integer not null primary key, author_name char(50) not null, lastModifiedBy integer not null, addedby integer not null)go
And some rows on it:INSERT INTO ParentVALUES (1, 'user_1'), (2, 'user_2'); INSERT INTO ChildVALUES (1, 'author_1', 1, 2), (2, 'author_2', 2, 1);
I need to update two lastModifiedBy and addedby columns after updating user_id in Parent table.So after this:UPDATE P SET user_id = D.user_idFROM Parent PJOIN (SELECT 10, 1 UNION ALL SELECT 20, 2) AS D(user_id, old)ON P.user_id = D.old
The Child table data must be somethink like this:author_id author_name lastModifiedBy addedby----------- ----------- -------------- -----------1 author_1 10 202 author_2 20 10
I have used following trigger but I do not believe this trigger is correct because nothing guarantees the order of rows in the Inserted and Deleted tables and I cannot just match based on some arbitrarily row number.CREATE TRIGGER trg ON ParentAFTER UPDATE AS BEGIN --Update lastModifiedBy Column --Update addedby Column ;WITH i AS (SELECT *, rn = ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM inserted), d AS (SELECT *, rn = ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM deleted), insert_delete AS (SELECT d.user_id AS old_user_id, i.user_id AS new_user_id FROM i JOIN d ON i.rn = d.rn) UPDATE C SET lastModifiedBy = D1.new_user_id, addedby = D2.new_user_id FROM Child C JOIN insert_delete D1 ON C.lastModifiedBy = D1.old_user_id JOIN insert_delete D2 ON C.addedby = D2.old_user_id; END
Thanks a lot.______________________