Comparing 2 tables and updating/inserting the main table

I have 2 tables: Main table with maybe 100,000+ rows and a Table1 with maybe 2000 rows.

I need to compare Table1 with the main table.
1.  If ID field in Table1 already exists in the Main table, then update that row in the Main table. 2. If ID in Table1 doesnt exists in Main table, then insert the row from Table1 into Main table.


Do I need to loop thru Main and Table1??
LVL 8
CamilliaAsked:
Who is Participating?
 
ralmadaCommented:
In sql 2005 you need to use one update and one insert:


Update a
set a.col1 = b.col1, a.col2 = b.col2, ... and so on... 
from Main a
inner join Table1 b on a.ID = b.ID

insert Main
select * from Table1 a
left join Main b on a.ID = b.ID
where b.ID is null

Open in new window


PS: Im assuming both tables structures are identical for the insert, if not you have to list them explicitly there in the select, so it should be

insert Main
select col1, col2, col3 from Table1 a
left join Main b on a.ID = b.ID
where b.ID is null
0
 
Jared_SCommented:
Don't loop, the joins will take care of that.
This will be your basic logic:

IF exists (select null from MainTable m where m.id = t1.id)
Begin
update m1 using records from table1 where the ID's match
End
Else
Begin
Insert into m1 (select rows from table1 where the ids aren't in the Main table)
End
0
 
CamilliaAuthor Commented:
yes, not sure why i thought of looping. Let me try
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
CamilliaAuthor Commented:
This line is not correct

IF exists (select null from MainTable m where m.id = t1.id)

I did this

IF EXISTS (SELECT ImagURL FROM Main WHERE ImagURL IN (SELECT ImageURL FROM Table1) )
0
 
ralmadaCommented:
excuse me, have you checked my comment? http:#a38410086

Also you don't have to do an IF ELSE there
0
 
CamilliaAuthor Commented:
yes, just noticed it. Let me try that as well.
0
 
Alpesh PatelAssistant ConsultantCommented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.