Groups | Blog | Home
all groups > sql server programming > july 2004 >

sql server programming : Compare 2 Tables Using Multiple Columns


<msnews.microsoft.com>
7/3/2004 10:21:44 PM
I have 2 tables...

table1
-------
col1
col2
col3
col4
col5
col6

table2
-------
col1
col2
col3
col4
col5
col6

I have data in table 1 that I need to delete from table2 ONLY where col1,
col2, and col3 are the exact same in col1,col2,col3 in table2. Then I need
to insert all rows from table1 into table2 where I just deleted that data
from table2. The remaining data in the other colums may be different, I
just need to do a compare on those 3 columns then insert the entire rows...
kinda like doing an update/insert where multiple columns match.

Any ideas?

Thanks a lot.

Uri Dimant
7/4/2004 11:03:40 AM
Hi
Its hard to inderstand since you did not post DDL + sample data
My guess is
DELETE FROM Table2 WHERE EXISTS
(
SELECT * FROM Table1 T1 WHETE T1.col1=Table2 .col1 AND T1.col2=Table2 .col2
AND T1.col3=Table2 .col3
)

INSERT INTO Table2 SELECT * FROM Table1 WHERE NOT EXISTS (SELECT * FROM
Table2 T2 WHETE T2.col1=Table1 .col1 AND T2.col2=Table1 .col2 AND
T2.col3=Table1 .col3)

PS. I am sorry , could be abe to test it.

[quoted text, click to view]

Harag
7/4/2004 11:40:09 AM
On Sun, 4 Jul 2004 11:03:40 +0200, "Uri Dimant" <urid@iscar.co.il>
[quoted text, click to view]


I'm also new to SQL but at first thought wouldn't the following work
better? This is untested and off the top of my newbie head so I don't
even know if its possible....

UPDATE Table2 T2 SET
T2.col4=T1.col4 ,
T2.col5=T1.col5 ,
T2.col6=T1.col6
WHERE EXISTS (SELECT * FROM Table1 T1
WHERE T2.col1=T1.col1 AND
T2.col2=T1.col2 AND
T2.col3=T1.col3
)
AddThis Social Bookmark Button