|
|
Question : Update Table from a temporary table
|
|
I have a table of real estate listings. For updating this data, I have gotten as far as manipulating the text file given to me and doing a bulk import into a second table, table_temp. It has the same structure as the main table. All of the rows have a unqiue MLS number and that column is in both the main table and temp table. Each day after the table_temp is loaded, it will have some records that are already in the main table, and the values will need updated, it will have some new records, and there will be some that are no longer there. How would I update the main table with the temp table in a stored proceedure and have it know whether to update each row (if the mls number already exists in the main table) or to insert the new row.
I will also need to delete any rows from the main table that were not in that day's temporary table. I was going to add a column to the main table called 'lastupdated' that would have the date the last time that row was updated or inserted in the stored proceedure. THen i could delete any rows that were not updated or inserted that day because they were not in the temp table.
Thanks in advance.
|
Answer : Update Table from a temporary table
|
|
Sure, there are other ways. I was just seeing if there was other data that you needed to keep, since there is, we can do it another way.
It is going to be a 3 step thing....a delete first, then update, then insert....
DELETE FROM mt FROM MyRealTable mt LEFTOUTER JOIN MyTempTable t ON t.MLSNumber = mt.MLSNumber WHERE t.MLSNumber IS NULL
UPDATE mt SET FieldToUpdate1 = t.FieldToUpdate1, FieldToUpdate2 = t.FieldToUpdate2, UpdatedDate = GETDATE() FROM MyTable mt JOIN MyTempTable t ON mt.MLSNumber = t.MLSNumber
INSERT INTO MyTable (MLSNumber, Field1, Field2, Field3) SELECT t.MLSNumber, t.Field1, t.Field2, t.Field3 FROM MyTempTable t LEFT JOIN JOIN MyTable mt ON t.MLSNumber = mt.MLSNumber WHERE mt.MLSNumber IS NULL
|
|
|
|
|