以下代码似乎不起作用。如果地址不存在,则不插入新记录。但是,如果地址确实存在,它会得到更新。
ALTER PROCEDURE [Users].[UpdateAddress]
@UserId int,
@Address1 varchar(100),
@Address2 varchar(100),
@Town varchar(100),
@County varchar(50),
@PostCode varchar(50),
@Country varchar(50),
@Type INT
AS
MERGE [Users].[Addresses] AS Target
USING (SELECT UserId FROM [Users].[Addresses] WHERE UserId = @UserId) AS Source
ON (Source.UserId = Target.UserId)
WHEN MATCHED THEN
UPDATE SET Target.Address1 = @Address1,
Target.Address2 = @Address2,
Target.Town = @Town,
Target.County = @County,
Target.Postcode = @Postcode,
Target.Country = @Country
WHEN NOT MATCHED BY TARGET THEN
INSERT ([UserId], [Address1], [Address2], [Town], [County], [PostCode], [Country], [Modified], [Type])
VALUES(@UserId, @Address1, @Address2, @Town, @County, @PostCode, @Country, GetDate(), @Type);