I am working on a data migration from a current prod table to a new table. I have prepared and tested the batch insert script based on the [Keycol] and [col8] (datetime) . This import is expected to go on for about 10 days.
--old table
SELECT TOP (1000) [Keycol],[col2],[col3],[col4],[col5],[col6],[col7],[col8],[col9],[col10]
FROM [dbo].[oldtable]
--newtable with identity column
SELECT TOP (1000) [NewIdentitycol],[Keycol],[col2],[col3],[col4],[col5],[col6],[col7],[col8],[col9],[col10]
FROM [dbo].[newtable]
I am preparing the insert/update/delete trigger on oldtable to capture any insert/update/delete after I started the import and do the same in my newtable.
I am new to triggers and most of the references I see in Google just tracks any one column for an update. I basically want to write trigger which captures update to any column in the tracked table and if that record is already imported into the new table, apply that update.
I took reference from https://www.sqlshack.com/solve-identity-crisis-sql-server/
Insert looks straight forward, but not sure what I tried in update/delete works for my case. I am going to do the POC, is there a better way of handing this. Please let me know.
CREATE TRIGGER Migration_trigger
ON dbo.oldtable
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;
-- INSERTS ONLY
INSERT INTO dbo.newtable
([Keycol],[col2],[col3],[col4],[col5],[col6],[col7],[col8],[col9],[col10])
SELECT Inserted.[Keycol],Inserted.[col2],Inserted.[col3],Inserted.[col4],Inserted.[col5],Inserted.[col6],Inserted.[col7],Inserted.[col8],Inserted.[col9],Inserted.[col10]
FROM Inserted
LEFT JOIN Deleted
ON Deleted.[Keycol] = Inserted.[Keycol]
WHERE Deleted.[Keycol] IS NULL;
-- DELETE ONLY already imported record
IF(SELECT [Keycol] from dbo.newtable n
join inserted on n.[keycol] = inserted.[keycol]
join deleted on inserted.[keycol] = Deleted.[keycol] where n.[Keycol]= Deleted.[Keycol]) IS NOT NULL
BEGIN
DELETE
FROM dbo.newtable
WHERE newtable.[Key] IN (
SELECT Deleted.[Keycol]
FROM Deleted
LEFT JOIN Inserted
ON Deleted.[Keycol] = Inserted.[Keycol]
WHERE Inserted.[Keycol] IS NULL);
END
-- UPDATE ONLY already imported record
IF(SELECT [Keycol] from dbo.newtable n
join inserted on n.[keycol] = inserted.[keycol]
join deleted on inserted.[keycol] = Deleted.[keycol] where n.[Keycol]= Deleted.[Keycol] and [Keycol]=inserted.[Keycol] ) IS NOT NULL
BEGIN
UPDATE dbo.newtable
SET [Keycol] = Inserted.[Keycol],[col2]=Inserted.[col2],[col3]=Inserted.[col3],[col4]=Inserted.[col4],[col5]=Inserted.[col5],[col6]=Inserted.[col6],
[col7]=Inserted.[col7],[col8]=Inserted.[col8],[col9]=Inserted.[col9],[col10]=Inserted.[col10]
FROM Inserted
INNER JOIN Deleted
ON Deleted.[Keycol] = Inserted.[Keycol]
INNER JOIN dbo.newtable
ON newtable.[Keycol] = Inserted.[Keycol]
END
END
Thanks