两个表之间的SQL查询“更新”

时间:2012-10-10 10:33:55

标签: sql ssms

我有一个包含两个表的数据库:

- October2012_ID包含两列:

a) OldId
b) NewId

- BNP其中还包含两列:

a)BankId
b)OrbId

我需要通过替换两列中包含的值来更新BNP表,如果这些值在表OldId中的列October2012_ID中可用。如果是这种情况,我需要使用BNP的值更新NewId中的列。

所以:

Update BNP
SET BNP.**BankId**=October2012_Id.NewId
where BNP.**BankId**=October2012_Id.OldId and October2012_Id.**BankId** is not null

还有:

Update BNP
SET BNP.**OrbId**=October2012_Id.NewId
where BNP.**OrbId**=October2012_Id.OldId and October2012_Id.**OrbId** is not null

我是SQL中的菜鸟,所以你能帮帮我吗?

2 个答案:

答案 0 :(得分:1)

UPDATE BNP
   SET BNP.OrbId=October2012_Id.NewId
  FROM October2012_Id
  JOIN BNP.OrbId=October2012_Id.OldId  --The default JOIN is INNER. Just shorthand for INNER JOIN
 WHERE October2012_Id.OrbId IS NOT NULL

您只需要将要使用FROM子句和JOIN的值的表格指定到要更新的表格上。

答案 1 :(得分:1)

您可以尝试在条件之间添加or

Update BNP
SET BNP.BankId=October2012_Id.NewId
from October2012_Id
where 
  (BNP.BankId=October2012_Id.OldId and October2012_Id.BankId is not null)
  or
  (BNP.OrbId=October2012_Id.OldId and October2012_Id.OrbId is not null)
相关问题