Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Inserting and Updating from an import table

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2006-06-09 : 08:48:44
SQLNewbie writes "I have a table 'ImportedListings' that is populated with data external to the database. This table is only used to hold the data until I can move it to the permanent table 'Listings' at which point 'ImportedListings' gets truncated to nothing. Both tables contain almost identical data and structure. There is a listing ID column available for joins.

Basically I need to compare each row in ImportedListing and if it already exists in Listing, UPDATE Listing with the new info. If the row in ImportedListing doesn't exist in Listing, I need to INSERT it.

Physically deleting rows from the listings table is not an option. Do you have any ideas on how I can do this? I initially tried using a temp table to hold the matching listing id's but I could not get figure out the update statement with this scenario.

Thanks for any help! I have been trying to hammer this out all night(I just started programming tsql)"

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-06-09 : 09:26:19
You need UPSERT

Update T
set col=S.col
from TargetTable T inner join SourceTable S
on T.id=S.id

Insert into TargetTable(columns)
Select columns from SourceTable S where not exists
(select * from TargetTable where id=S.id)

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -