What I am trying to achieve:
When someone updates the Car table with (RegNum, VinNumber, CarMakeID etc) I need to put this in the audit table.
In the example below, I have selected CarID = 1 and ChangeItem = 1 (which I want the code to use the first part of the case).
If I was to select ChangeItem2 I would want it to update the VinNumber in the Car Table and insert the deleted.VinNumber and Inserted.VinNumber into the audit table.
DECLARE @CarID INT
DECLARE @ChangedItem INT
DECLARE @Input VARCHAR(50)
SET @CarID = 1
SET @ChangedItem = 1
SET @Input = 'LR44 GH345'
UPDATE CAR
(
CASE
WHEN @ChangedItem = 1 THEN
SET RegNum = @Input
OUTPUT @CarID, @ChangedItem, deleted.RegNum, inserted.RegNum INTO CarAudit (CarID, CarAuditObjectID, OldValue ,NewValue)
WHERE CarID = @CarID
WHEN @ChangedItem = 2 THEN
SET VinNumber = @input
OUTPUT @CarID, @ChangedItem, deleted.RegNum, inserted.RegNum INTO CarAudit (CarID, CarAuditObjectID, OldValue ,NewValue)
WHERE CarID = @CarID
END
)
If anyone has a better way of doing this altogether please share, I am not rigid in staying with this design.
Many thanks for any assistance.
Jay.
For anyone that stumbled across this.
I wanted to avoid the use of triggers so putting it in as a sproc with the below code: