我正在尝试使用MERGE语句更新Sql Server 2012表中的记录。我有我的目标表和我的源登台表。当ID字段匹配时,我想用来自源的匹配行替换整行,如果不匹配,则将该行作为新行添加到表中。我不知道在更新集(?)之后要写什么来实现这一点。这是我的代码:
USE DataCompany
MERGE INTO MasterAddress ma
USING MasterAddressStaging ms
ON MasterAddress.ID = MasterAddressStaging.ID
WHEN MATCHED THEN
UPDATE SET (?)
WHEN NOT MATCHED THEN
INSERT (ID
,CompanyName
,CompanyNumber
,RegAddress_CareOf
,RegAddress_POBox
,RegAddress_AddressLine1
,RegAddress_AddressLine2
,RegAddress_PostTown
,RegAddress_County
,RegAddress_Country
,RegAddress_PostCode)
VALUES (ms.ID
,ms.CompanyName
,ms.CompanyNumber
,ms.RegAddress_CareOf
,ms.RegAddress_POBox
,ms.RegAddress_AddressLine1
,ms.RegAddress_AddressLine2
,ms.RegAddress_PostTown
,ms.RegAddress_County
,ms.RegAddress_Country
,ms.RegAddress_PostCode);
感谢您的帮助
答案 0 :(得分:2)
USE DataCompany
MERGE INTO MasterAddress ma
USING MasterAddressStaging ms
ON ma.ID = ms.ID
WHEN MATCHED THEN
UPDATE SET ma.CompanyName = ms.CompanyName,
ma.CompanyNumber = ms.CompanyNumber,
ma.RegAddress_CareOf =ms.RegAddress_CareOf,
ma.RegAddress_POBox =ms.RegAddress_POBox,
ma.RegAddress_AddressLine1 = ms.RegAddress_AddressLine1,
ma.RegAddress_AddressLine2 = ms.RegAddress_AddressLine2,
ma.RegAddress_PostTown = ms.RegAddress_PostTown,
ma.RegAddress_County = ms.RegAddress_County,
ma.RegAddress_Country = ms.RegAddress_Country,
ma.RegAddress_PostCode = ms.RegAddress_PostCode
WHEN NOT MATCHED THEN
INSERT (ID
,CompanyName
,CompanyNumber
,RegAddress_CareOf
,RegAddress_POBox
,RegAddress_AddressLine1
,RegAddress_AddressLine2
,RegAddress_PostTown
,RegAddress_County
,RegAddress_Country
,RegAddress_PostCode)
VALUES (ms.ID
,ms.CompanyName
,ms.CompanyNumber
,ms.RegAddress_CareOf
,ms.RegAddress_POBox
,ms.RegAddress_AddressLine1
,ms.RegAddress_AddressLine2
,ms.RegAddress_PostTown
,ms.RegAddress_County
,ms.RegAddress_Country
,ms.RegAddress_PostCode);
参见示例here