如何从SQL Server中的不同值更新公共列值?

时间:2015-04-20 13:11:22

标签: sql sql-server sql-server-2008

我有两张桌子。我的第一个table A包含

Tran_Particular | Dr_Tran_Amt | BeneficiaryName | PRNNo 

列。

我的第二张表B包含

BeneficiaryName | Dr_Tran_Amt | PRNNo

列。

我想要更新表格A.PRNNo但是当我在BeneficiaryNameDr_Tran_Amt更新时,它只会更新第一个值。但是在table B中存在两个PRNNO,而在table A中还存在两个不同的Tran_Particular。我想更新唯一的PRNNO wrt Tran_ParticularBeneficiaryNameDr_Tran_Amt

查询

update A
  set a.PRNNo = b.PRNNo
from A a
  inner join B b
    on  a.Dr_Tran_Amt= b.Amount
    and a.BeneficiaryName = b.BeneficiaryName;

如何在SQL server中更新它。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

下面的代码应该只为您提供第一个匹配的行(最低的PRNNo值):

UPDATE A
  SET a.PRNNo = b.PRNNo
FROM A a
  INNER join B b
    ON  a.Dr_Tran_Amt = b.Amount
    AND a.BeneficiaryName = b.BeneficiaryName
    AND b.PRNNo = (SELECT MIN(c.PRNNo) FROM B c WHERE c.BeneficiaryName = B.BeneficiaryName AND c.Dr_Tran_Amt = b.Dr_Tran_Amt);