MERGE SQL Server主键冲突

时间:2018-05-28 04:06:13

标签: sql-server tsql primary-key

我有可能成功执行下面的sql语句吗? 目前,我在下面的查询中收到主要密钥违规。

我想要的是,当第一条记录被插入到目标表中并且如果有另一个相同的主键将被插入时,它应该执行UPDATE而不是INSERT以避免主键违规,但我不知道不知道在实际的sql脚本中写它。据我所知,我只有以下脚本。

// User-Defined Tabled Type
DECLARE @tvpEmailType dbo.EmailType

INSERT @tvpEmailType VALUES ('mail@mail.com', 1)
INSERT @tvpEmailType VALUES ('mail@mail.com', 0)

MERGE dbo.EmailRepo AS TARGET
USING (SELECT DISTINCT * FROM @tvpEmailType) AS SOURCE
    ON (TARGET.Email = SOURCE.Email)
WHEN MATCHED AND TARGET.Status <> SOURCE.Status THEN
    UPDATE SET TARGET.Status = SOURCE.Status
WHEN NOT MATCHED THEN
    INSERT (Email, Status) VALUES (SOURCE.Email, SOURCE.Status);

1 个答案:

答案 0 :(得分:1)

宾果

DECLARE @i table (iden int identity, email varchar(40), status bit);
DECLARE @t table (email varchar(40) primary key, status bit);

INSERT @i VALUES ('mail@mail.com', 1), ('mail@mail.com', 0)

MERGE @t AS TARGET
USING ( select email, status 
        from ( select email, status
                    , row_number() over (partition by email order by iden desc) as rn
                from @i
             ) t
             where t.rn = 1
      ) AS SOURCE
   ON TARGET.Email = SOURCE.Email
WHEN MATCHED THEN
    UPDATE SET TARGET.Status = SOURCE.Status
WHEN NOT MATCHED THEN
    INSERT (Email, Status) VALUES (SOURCE.Email, SOURCE.Status);

select * from @t