I am using staging tables to perform validation and insert into live.
Suppose I have a table PERSONS
TABLE Persons
(
Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
HouseNumber int,
)
and a STAGING TABLE as follows
TABLE Persons_Staging
(
Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
HouseNumber varchar(255),
)
I need to write a procedure to transfer data from the staging table to the live table while ensuring no duplicates are inserted. How can I achieve that?
Thanks in advance
Use the MERGE
command.
Something like this:
MERGE
INTO Persons AS TARGET
USING Persons_Staging AS SOURCE
ON TARGET.ID = SOURCE.ID
--WHEN MATCHED
-- THEN UPDATE???
WHEN NOT MATCHED BY TARGET
THEN INSERT (Id , LastName , FirstName, HouseNumber)
VALUES (SOURCE.Id , SOURCE.LastName , SOURCE.FirstName, SOURCE.HouseNumber)
-- WHEN NOT MATCHED BY SOURCE
-- THEN DELETE???
;
If you want to update existing records you uncomment the UPDATE
part and add a suitable update clause. The same with the delete part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With