SQL Merge语句在存储过程中不起作用

时间:2013-07-31 10:02:00

标签: sql sql-server tsql stored-procedures

以下代码似乎不起作用。如果该地址不存在,则不会插入新记录。但是,如果地址确实存在,则会更新。

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);

1 个答案:

答案 0 :(得分:15)

您的来源不应该依赖目标表。请尝试改为:

MERGE [Users].[Addresses] AS Target
USING (select @UserID,@Address1,@Address2,@Town,@County,@PostCode,@Country,@Type)
    AS Source (UserID,Address1,Address2,Town,County,PostCode,Country,Type)
ON (Source.UserId = Target.UserId)
WHEN MATCHED THEN
    UPDATE SET Target.Address1 = Source.Address1,
    Target.Address2 = Source.Address2,
    Target.Town = Source.Town,
    Target.County = Source.County,
    Target.Postcode = Source.Postcode,
    Target.Country = Source.Country
WHEN NOT MATCHED BY TARGET THEN
    INSERT ([UserId], [Address1], [Address2], [Town], [County], [PostCode], [Country], [Modified], [Type])
    VALUES(Source.UserId, Source.Address1, Source.Address2, Source.Town, Source.County, Source.PostCode, Source.Country, GetDate(), Source.Type);

目前,您正在创建一个零行Source行集,因此合并中没有任何反应。