我正在使用sql server,我有一个SQL查询,它将#tempEmployee表合并到主employee表中,然后删除tempEmployee表。
在某些情况下,当任何行由于某些约束等而无法合并时,我想跟踪该行,以便我可以修复错误原因并再次启动合并操作。
我这样做是为了将批量数据插入到employee表中。我在C#中创建#tempEmployee表,然后将此#tempEmployee表发送到sql server以与主employee表合并。
例如: -
MERGE INTO Employee T
USING #TempTable Temp ON T.businessentityid = temp.businessentityid
WHEN MATCHED
THEN
UPDATE SET T.BusinessEntityID = temp.BusinessEntityID
,T.DepartmentID = temp.DepartmentID
,T.ShiftID = temp.ShiftID
,T.StartDate = temp.StartDate
,T.EndDate = temp.EndDate
,T.ModifiedDate = temp.ModifiedDate
WHEN NOT MATCHED
THEN
INSERT(BusinessEntityID,DepartmentID,ShiftID,StartDate,EndDate,ModifiedDate)
VALUES( temp.BusinessEntityID, temp.DepartmentID, temp.ShiftID,
temp.StartDate, temp.EndDate, temp.ModifiedDate)
我的问题是,有没有办法知道哪一行在合并操作期间失败了?
答案 0 :(得分:1)
如果"在合并操作期间哪一行失败"是不匹配的行,您可以使用OUTPUT子句:
MERGE INTO Employee T
USING #TempTable Temp ON T.businessentityid = temp.businessentityid
WHEN MATCHED
THEN UPDATE
SET T.BusinessEntityID = temp.BusinessEntityID
,T.DepartmentID = temp.DepartmentID
,T.ShiftID = temp.ShiftID
,T.StartDate = temp.StartDate
,T.EndDate = temp.EndDate
,T.ModifiedDate = temp.ModifiedDate
WHEN NOT MATCHED
THEN INSERT(BusinessEntityID,DepartmentID,ShiftID,StartDate,EndDate,ModifiedDate)
VALUES( temp.BusinessEntityID, temp.DepartmentID, temp.ShiftID, temp.StartDate, temp.EndDate, temp.ModifiedDate)
OUTPUT inserted.* into ***some table***
https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql