根据ID

时间:2016-06-03 10:27:11

标签: sql sql-server sql-update

我需要从另一个表更新一个表。我必须根据某些ID号更新所有列,例如id = 5和id = 10。我试过了

update Somedatabase.dbo.CONTHIST
set Somedatabase.dbo.CONTHIST.id = p.id
from SomedatabaseTest.dbo.CONTHIST p
where Somedatabase.dbo.CONTHIST.id= 17448
and p.id = 17448

所以你可以看到我试图从SomedatabaseTest更新它,我已经恢复了数据,但即使我不知道如何更新某些id的所有列和数据。我尝试了并进行了一些更改,但我忘了提到除了 id 我每个记录都有 cnkey ,一个用户可以有几个记录并自动有几个不同cnkey-S。那你能再帮我一次吗?我期待着你的帮助! :d

4 个答案:

答案 0 :(得分:0)

containsValue

TABLE2是数据的来源

答案 1 :(得分:0)

首先在两个表之间建立关系,然后根据需要更新列。

update Somedatabase.dbo.CONTHIST
set Somedatabase.dbo.CONTHIST.id = p.id 
[add as many columns as you need to update here]
from Somedatabase.dbo.CONTHIST inner join SomedatabaseTest.dbo.CONTHIST p
on Somedatabase.dbo.CONTHIST.id = p.id 
where Somedatabase.dbo.CONTHIST.id= 17448
and p.id = 17448 and p.cnkey = [something];

答案 2 :(得分:0)

如果我理解正确,你需要的是:

UPDATE Somedatabase.dbo.CONTHIST
SET a.id = p.id,
    a.column1 = p.column1,
    a.column2 = p.column2,
    ...
FROM SomedatabaseTest.dbo.CONTHIST p
INNER JOIN Somedatabase.dbo.CONTHIST a
ON a.id = p.id
WHERE a.id = 17448

答案 3 :(得分:0)

我认为这就是你要找的东西(我不会更新id,因为它是PK,值必须相同)

update Somedatabase.dbo.CONTHIST
  set Somedatabase.dbo.CONTHIST.field1 = p.field1,
      [.....]
      Somedatabase.dbo.CONTHIST.fieldn = p.fieldn
from SomedatabaseTest.dbo.CONTHIST p
where Somedatabase.dbo.CONTHIST.id = p.id
  and Somedatabase.dbo.CONTHIST.cnKey = p.cnKey
  and p.id=17448;