通过合并语句记录操作的最佳方式,可能具有在TSQL中识别错误的能力



我使用Merge语句来执行表填充,我正在寻找一种最好的方法来实现Merge语句的错误记录。

最初,我想记录由merge语句执行的操作(例如插入、更新、删除操作)所影响的行数,而不是详细的行内容。但是,如果错误出现,记录的详细信息可能不足以确定错误的原因。

第二个选项是将Merge执行的所有行记录到日志表中。然而,缺点是每个业务表需要一个日志记录表;并保存所有的数据。

但是,由于merge执行原子操作,这意味着当发生错误时没有数据要记录。因此,错误日志功能可能用于跟踪表填充逻辑中的潜在错误(如果错误,请纠正)。

我想要一种在merge语句中记录错误的方法,这样我就可以识别错误,甚至可以恢复数据。

如有任何建议,不胜感激。

要保存Merge的结果,使用Merge OUTPUT INTO将所有受影响的行插入到表中,以及下面的@@RowCount:

DECLARE @ChangedTable Table (
Action Varchar(20),
TargetProductID Int,
TargetProductName Varchar(100),
TargetRate Money,
SourceProductID Int, 
SourceProductName Varchar(100), 
SourceRate Money
)
--Synchronize the target table with
--refreshed data from source table
MERGE Products AS TARGET
USING UpdatedProducts AS SOURCE 
ON (TARGET.ProductID = SOURCE.ProductID) 
--When records are matched, update 
--the records if there is any change
WHEN MATCHED AND TARGET.ProductName <> SOURCE.ProductName 
OR TARGET.Rate <> SOURCE.Rate THEN 
UPDATE SET TARGET.ProductName = SOURCE.ProductName, 
TARGET.Rate = SOURCE.Rate 
--When no records are matched, insert
--the incoming records from source
--table to target table
WHEN NOT MATCHED BY TARGET THEN 
INSERT (ProductID, ProductName, Rate) 
VALUES (SOURCE.ProductID, SOURCE.ProductName, SOURCE.Rate)
--When there is a row that exists in target table and
--same record does not exist in source table
--then delete this record from target table
WHEN NOT MATCHED BY SOURCE THEN 
DELETE
--$action specifies a column of type nvarchar(10) 
--in the OUTPUT clause that returns one of three 
--values for each row: 'INSERT', 'UPDATE', or 'DELETE', 
--according to the action that was performed on that row
OUTPUT $action, 
DELETED.ProductID AS TargetProductID, 
DELETED.ProductName AS TargetProductName, 
DELETED.Rate AS TargetRate, 
INSERTED.ProductID AS SourceProductID, 
INSERTED.ProductName AS SourceProductName, 
INSERTED.Rate AS SourceRate
INTO @ChangedTable;
select * from @ChangedTable;
SELECT @@ROWCOUNT;

如有任何意见,不胜感激。

表:

--Create a target table
CREATE TABLE Products
(
ProductID INT PRIMARY KEY,
ProductName VARCHAR(100),
Rate MONEY
) 
GO
--Insert records into target table
INSERT INTO Products
VALUES
(1, 'Tea', 10.00),
(2, 'Coffee', 20.00),
(3, 'Muffin', 30.00),
(4, 'Biscuit', 40.00)
GO
--Create source table
CREATE TABLE UpdatedProducts
(
ProductID INT PRIMARY KEY,
ProductName VARCHAR(100),
Rate MONEY
) 
GO
--Insert records into source table
INSERT INTO UpdatedProducts
VALUES
(1, 'Tea', 10.00),
(2, 'Coffee', 25.00),
(3, 'Muffin', 35.00),
(5, 'Pizza', 60.00)
GO
SELECT * FROM Products
SELECT * FROM UpdatedProducts
GO

我想记录受操作影响的行数(例如:插入、更新、删除操作)由merge语句执行

要做到这一点,你已经在路上了!

基本上,您需要做的就是将SELECT@ChangedTable更改为:

SELECT Action, COUNT(*) 
FROM @ChangedTable
GROUP BY Action;

,你应该得到这样的内容:

Action  (No column name)
DELETE        1
INSERT        1
UPDATE        2

这就是你想要的吗??

最新更新