Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - copy data from staging table

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

like image 304
dopplesoldner Avatar asked Nov 16 '12 10:11

dopplesoldner


1 Answers

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.

like image 161
Albin Sunnanbo Avatar answered Nov 14 '22 02:11

Albin Sunnanbo