在SQL Server

时间:2016-03-28 19:50:16

标签: sql-server

我在SQL Server中有一个表,我希望插入新记录或在值已更改时更新记录。 merge命令似乎已关闭,但如果该记录已存在,则无论如何都会更新它。我希望找到的功能是"跳过"如果源的每列与目标相同。

以下是一个例子:

CREATE TABLE #Clients (
    ClientID int PRIMARY KEY,
    FirstName varchar(20),
    InsertedDate datetime default getdate(),
    ModifiedDate datetime default getdate()
    );

INSERT INTO #Clients (ClientID, FirstName)
VALUES (1, 'Fred'), (2, 'Barney'), (3, 'Betty');

CREATE TABLE #Source (
    ClientID int PRIMARY KEY,
    FirstName varchar(20),
    InsertedDate datetime default getdate(),
    ModifiedDate datetime default getdate()
    );

INSERT INTO #Source (ClientID, FirstName)
VALUES (1,'Fred'), (2, 'Fred Jr.'), (4, 'Wilma');

USE tempdb;
GO
BEGIN TRAN;
MERGE #Clients AS C
USING #Source AS S ON (C.ClientID = S.ClientID) 
WHEN NOT MATCHED BY TARGET
    THEN INSERT(ClientID, FirstName) VALUES(S.ClientID, S.FirstName)
WHEN MATCHED 
    THEN UPDATE SET C.FirstName = S.FirstName, ModifiedDate = GETDATE()
WHEN NOT MATCHED BY SOURCE
    THEN DELETE 
OUTPUT $action, inserted.*, deleted.*;
GO 

有没有办法把它写成只更新一条记录?

0 个答案:

没有答案