I am merging a table and want to retain the previous value in a seperate table, along with the column that was updated.
I have got it working to retain the values, but want to know how I can retain the column name.
Existing table: tTable1
qID qUnits qDateTime
1001 4900 2022-09-13 12:00:00.000
1002 6800 2022-09-14 15:00:00.000
1003 7400 2022-09-14 13:00:00.000
Temp Table (holds updated values): #updateValues
qID qOriginalUnit qUpdatedUnit
1001 4900 8900
1002 6800 13400
1002 7400 16500
The code i'm using currently, to output what the existing value was, before the update;
DECLARE @auditRecords TABLE(qID INT, PreviousValue VARCHAR(100)
MERGE tTable1 AS TARGET
USING #updateValues AS SOURCE
ON (SOURCE.qID = TARGET.qID)
WHEN MATCHED
THEN UPDATE SET
TARGET.qUnits = SOURCE.qUpdatedUnit
OUTPUT SOURCE.qID, SOURCE.qOriginalUnit INTO @auditRecords(qID,PreviousValue);
I'd like to be able to include the column name that was updated, in this instance QUnits, so the output would look like the following;
qID PreviousValue UpdatedColumn
1001 4900 qUnits
1002 6800 qUnits
1003 7400 qUnits