Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling live table with records from staging table

I have 2 Identical tables in SQL Server 2008, one is the "Live" table which my application is constantly using. I am pulling down new records periodically during the day and inserting them into a "staging" table from which I need to pull new records and insert into the Live table. I don't want any duplicates inserted just in case some records are overlapped. There are 10 columns which I need to look at to see if an identical record exists, I have looked at some TSQL examples but none so far are working, I have also considered dealing with the dupes and just reporting on the DISTINCT values but DISTINCT one works for one record, I need it to work for 10. Any suggestions?

Thanks, Sam

like image 499
Sam Cromer Avatar asked Mar 30 '12 14:03

Sam Cromer


People also ask

What comes after staging table?

After a staging table is properly configured based on source data, the staging data contents can be transferred to permanent data table(s) in a data warehouse or relational database.

What is the purpose of staging tables?

The staging table is a temporary table that holds all of the data that will be used to make changes to the target table, including both updates and inserts.

How do you display table records?

Double-click the table name in the grid. Select names of tables in the grid, then right-click and select Display Rows from the shortcut menu, or select Display Rows from the File menu.

How do you add a column to a staging table?

You use the Add/Edit Staging Table window to select the columns on the target table that can be populated by the staging table. then creates each staging table column with the same data types as the corresponding column in the target table.


1 Answers

This is an ideal use case for NOT EXISTS - you can check on as many criteria as you like to verify you won't insert a dupe.

INSERT INTO Live
SELECT <fields>
FROM Staging s
WHERE NOT EXISTS (SELECT 1
                  FROM Live l
                  WHERE s.FieldA = l.FieldA
                  AND s.FieldB = l.FieldB
                  <all your checks here>...)
like image 95
JNK Avatar answered Oct 17 '22 03:10

JNK