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
 How to UPDATE table using data from another table

Author  Topic 

robertnzana
Starting Member

42 Posts

Posted - 2008-05-08 : 14:25:55
I have 2 tables...

Table1: FullName, City, State, Data1
Table 2: FullName, City, State, Data1, Data2, Data3

This is what I want to do...
1. For every record that is in BOTH tables I want to UPDATE TABLE 2 with the data from Table 1.
2. Then, if there are "extra"/new records in table 1 I want to append them to Table 2.

How would I do this? Can you provide syntax? I'm new.

Thanks.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-05-08 : 14:29:52
Where will values for Data2 & Data3 come from? they are not in table1. ALso what is PK of each table?
Go to Top of Page

eralper
Yak Posting Veteran

66 Posts

Posted - 2008-05-08 : 14:42:19
Hello,

I guess the following statements may help you


UPDATE EY_Table2
SET
Data1 = t1.Data1
FROM EY_Table2 t2 (NoLock)
INNER JOIN EY_Table1 t1 (NoLock)
ON t1.FullName = t2.FullName
AND t1.City = t2.City
AND t1.[State] = t2.[State]

INSERT INTO EY_Table2 (
FullName, City, [State], Data1
)
SELECT
t1.FullName, t1.City, t1.[State], t1.Data1
FROM EY_Table1 t1 (NoLock)
LEFT JOIN EY_Table2 t2 (NoLock)
ON t1.FullName = t2.FullName
AND t1.City = t2.City
AND t1.[State] = t2.[State]


Eralper
http://www.kodyaz.com



-------------
Eralper
http://www.kodyaz.com
Go to Top of Page
   

- Advertisement -