SELECT
[EmpTemplateHistoryID],
[EmployeeID],
[TemplateID],
[AdjustStatus],
[AdjustReason],
[AdjustTime],
isnull((select top 1 [EmpTemplateHistoryID] from [EmpPRTemplateHistory] where [EmployeeID]=a.EmployeeID),NEWID()) [AdjustBeforeHistoryID],
[Remark],
getdate()
FROM @DataTable a
where NOT EXISTS
(SELECT * FROM [EmpPRTemplateHistory] WHERE
[EmployeeID] = a.[EmployeeID]
AND TemplateID = a.TemplateID
AND AdjustReason=a.AdjustReason
)
[EmpTemplateHistoryID],
[EmployeeID],
[TemplateID],
[AdjustStatus],
[AdjustReason],
[AdjustTime],
isnull((select top 1 [EmpTemplateHistoryID] from [EmpPRTemplateHistory] where [EmployeeID]=a.EmployeeID),NEWID()) [AdjustBeforeHistoryID],
[Remark],
getdate()
FROM @DataTable a
where NOT EXISTS
(SELECT * FROM [EmpPRTemplateHistory] WHERE
[EmployeeID] = a.[EmployeeID]
AND TemplateID = a.TemplateID
AND AdjustReason=a.AdjustReason
)