Saturday, December 6, 2008

Compare two tables, then update the difference.

Version 1:

-- This script would compare table2 to table1 (one way), then update those updated rows in table2 to table1.
-- Note: The ID of rows existed in table2, but not existes in table1, will be ignored.


UPDATE t1
SET t1.name=t2.name, t1.email=t2.email
FROM (
SELECT mm.id,mm.name,mm.email
FROM tb_name2 mm
WHERE NOT EXISTS
(
SELECT 1 FROM tb_name m
WHERE m.ID=mm.ID
And m.name=mm.name
And m.email=mm.email
)
) as t2, tb_name as t1
WHERE t2.id=t1.id


Version 2:

-- This script would compare table2 to table1 (one way), then update those updated rows in table2 to table1.
-- Note: The ID of rows existed in table2, but not existes in table1, will be ignored.


UPDATE t1
SET t1.name=t2.name, t1.email=t2.email
FROM (
SELECT mm.id,mm.name,mm.email
FROM tb_name2 mm
WHERE NOT EXISTS
(
SELECT 1 FROM tb_name m
WHERE m.ID=mm.ID
And m.name=mm.name
And m.email=mm.email
)
) as t2
INNER JOIN tb_name as t1
ON t2.id=t1.id

No comments: