Reputation: 231
I have a table called 'Day Zero' which contains a listing_id column, address column and status column. The listing_id is always unique and is an int data type. The status column in every row is Existing
Each day, I get two text files, one called Listings, and the Other called Sold, and I use BULK insert to import the data directly into the table, the data is these two text files contains only a listing_id and address column.
What I'm trying to figure out, is how to import the data from these files into the table with the following logic:
if listing_id
exists in day zero
file and listings
file then do not import new row and change status
on existing row to 'updated'
if listing_id
does not exist in day zero
file and exists in listing_file then insert new row and change status
to 'new'
if listing id exists in day zero
file and exists in sold_file
then do not import new row and change status
on existing row to 'sold'
if listing_id
does not exist in day zero
file and exists in sold_file
then insert new row and change status
to 'unknown_sale_event'
Upvotes: 0
Views: 338
Reputation: 222402
You could load each file in a separate temporary table, and then implement the logic using SQL Server's merge
syntax:
The following query merges data from the LISTINGS file (assuming that the file was loaded in temporary table #listings
):
merge day_zero d
using #listings l on (l.listing_id = d.listing_id)
when matched
then update set d.status = 'UPDATED'
when not matched by target
then insert(listing_id, address, status)
values(l.listing_id, address, 'NEW')
And here is the equivalent query for the SALES file:
merge day_zero d
using #sold s on (s.listing_id = d.listing_id)
when matched
then update set d.status = 'SOLD'
when not matched by target
then insert(listing_id, address, status)
values(s.listing_id, address, 'UNKNOWN_SALE_EVENT')
Upvotes: 1