从另一个表更新数据

时间:2012-07-10 09:07:04

标签: sql sql-server

我需要更新另一个表中的一些数据..

我想简单地将table1中col1的数据转换为table2中的col1,这些行位于相同的位置,因此确实存在任何id比较需要完成的事情..

我该怎么做?

-----------------------------------------
Db1.Table1 (Take yearModel from this table to update Table3)
-----------------------------------------
imgid          | int | PK |
yearModel      | int |
-----------------------------------------


-----------------------------------------
Db2.Table2 (Go by this table to update Table3)
-----------------------------------------
imgid          | int | PK |
uploadId       | int | FK (With table3.uploadId) |
------------------------------------------

------------------------------------------
Db2.Table3 (Update this table with the yearModel from table1)
-------------------------------------------
uploadId        | int | PK |
uploadYearModel | int |

抱歉,我的数据库diagaram“thingy”因某些奇怪的原因而崩溃了.. :( 我希望你能实现这个想法

我还应该提到Table1位于另一个数据库中......我不确定这是否重要......但是......:)

提前致谢!

3 个答案:

答案 0 :(得分:2)

如果您在两个表格中都有一个公共密钥列。这个键列在两个表中具有相同的值(它们引用两个表中的相同行)然后在查询下面应该起作用:

UPDATE  Table1
SET     Column1 = t2.Column1
FROM    Table2 t2 INNER JOIN Table1 t1 ON t2.KeyColumn = t1.KeyColumn

修改

UPDATE Table3 
SET    uploadYearModel = t1.yearModel 
FROM   Table1 t1
       INNER JOIN Table2 t2 ON t2.imgid = t1.imgid
       INNER JOIN Table3 t3 ON t3.uploadId = t2.uploadId

答案 1 :(得分:0)

UPDATE table2 SET col1=(
       SELECT top 1 col1 FROM table1 WHERE table1.id=table2.id
)

答案 2 :(得分:0)

更新现有记录:

UPDATE table2 
SET table2.c1 = table1.c1, 
table2.c2 = table1.c2,
table2.c3 = table1.c3
FROM table1, table2 
WHERE table1.c1 = table2.c1