UPSERT - CAPTURE UPDATED ROWS INTO ANOTHER AUDIT TABLE

RJ 286 Reputation points
2025-01-20T17:01:10.7433333+00:00

Hi there,

I'm trying to do soft delete on a target table which are not in source. Basically if the ID is not in source but ID is in target, update that RecordStatusKey of that specific target ID.

I would like to capture the records updated in merge. Is that possible?

	DECLARE @MergeOutputTable TABLE
	([Action] varchar(20), 
	 [Id] bigint
	)  
    -- Execute the Merge for Insert and Update    
	MERGE INTO [dbo].[TargetTbl] AS T 
	
	USING [dbo].[SourceTbl] AS S 
	
	ON T.[Id] = S.[Id]
	WHEN NOT MATCHED BY SOURCE THEN
	UPDATE SET 
	T.[RecordStatusKey]			= 2
	
	Would like to capture the records that got updated into a Audit table.
	--INSERT INTO [Audit].[TrackALLDeletions] --how can i do this?
	--VALUE (T.[Id], getdate() DateOfDeletion)

	OUTPUT $action, INSERTED.[Id]
	INTO @MergeOutputTable;
 -- Capture row counts
	SELECT 
	    @RowsWritten = SUM(CASE WHEN [action] = 'INSERT' THEN 1 ELSE 0 END),
	    @RowsUpdated = SUM(CASE WHEN [action] = 'UPDATE' THEN 1 ELSE 0 END),
	    @RowsDeleted = SUM(CASE WHEN [action] = 'DELETE' THEN 1 ELSE 0 END)
	FROM @MergeOutputTable;
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,395 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,685 questions
0 comments No comments
{count} votes

Accepted answer
  1. Naomi Nosonovsky 8,126 Reputation points
    2025-01-20T19:38:40.6633333+00:00

    Your @mergeOutputTable contains the records you updated.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.