UPDATE m SET
col2 = t.col2,
col3 = t.col3 -- etc. - all columns except Customer_Number
FROM dbo.Master_File AS m
INNER JOIN
(
SELECT
Customer_Number, rn = ROW_NUMBER() OVER
(
PARTITION BY Customer_Number ORDER BY [timestamp_column] DESC
), col2, col3, ... etc ...
FROM dbo.Temp_Table
) AS t
ON m.Customer_Number = t.Customer_Number
WHERE t.rn = 1;
INSERT dbo.Master_File(Customer_Number, col2, col3, ...etc...)
SELECT Customer_Number, col2, col3, ...etc...
FROM
(
SELECT
Customer_Number, rn = ROW_NUMBER() OVER
(
PARTITION BY Customer_Number ORDER BY [timestamp_column DESC
),
col2, col3, ...etc...
FROM dbo.Temp_Table AS t
WHERE NOT EXISTS
(
SELECT 1 FROM dbo.Master_File AS m
WHERE m.Customer_Number = t.Customer_Number
)
) AS x WHERE rn = 1;
这会处理源表中不存在于目标中的多行。我对必须调整的列名做出了假设。
MERGE
可能很诱人,但是我回避它有几个原因:
- 语法令人生畏并且难以记忆......
- 除非您有意添加特定的锁定提示,否则您不会获得比上述方法更多的并发性...
- 有许多未解决的错误,
MERGE
可能还有更多尚未被发现的错误......
我最近也在这里发布了一个警告提示,并在这里收集了一些其他意见。