仅在ID匹配时更新记录

时间:2010-01-05 23:18:09

标签: sql sql-server sql-server-2005 sql-update

如何根据当前数据库中的记录更新单独数据库中表中的数据?

例如,我想使用数据库“database_new”中包含的值更新名为“database_old”的数据库中的“status”字段。我当前的数据存在于数据库“database_new”中。我想只在record_id字段匹配时更新“database_old”数据库中的记录。 “status”和“record_id”字段存在于两个数据库的“products”表中。正如我所说,字段“status”应该使用“database_new”中的值进行更新,但只有在record_id匹配时才会更新。

这是一个MS SQL 2005数据库。

2 个答案:

答案 0 :(得分:3)

update database_old.dbo.products
set status = new.status
from database_new.dbo.products new
where database_old.dbo.products.record_id = new.products.record_id

答案 1 :(得分:0)

如果两个数据库都在同一台服务器上,则只使用3部分名称Database.dbo.TableName。例如:

update old
set old.status = new.status
from database_old.dbo.products old
inner join database_new.dbo.products new
on old.record_id = new.record_id

如果它们位于不同的服务器上,那么您需要拥有一个链接服务器,然后使用4部分名称。

相关问题