About 6 months ago I wrote about the way to create a log sheet in Excel with VBA.
Nowadays, as far as I am doing a small upgrade from MS Excel to MS SQL Server 🙂 , I was interested to find a way to repeat the exercise. Thus, with the power of SQL Server, there was no doubt that a such task is possible.
How to do it?
First, create a table where to log the changes. Then, generate a trigger with SQL. Now, let’s imagine that we want to build a table, that follows the changes of the Money table from this example.
Pretty much, this is how the empty table with logs would look like:
We have columns Id, ChangeDate, Command and UserName, which would be filled out automatically on a change. The other columns are OldCell, NewCell, NewPaidPerCell and OldPaidPerCell. They would be filled out in case of update, delete or insert is carried out (also automatically btw) :).
Thus, this is what you will get in the log table, after doing 2 delete commands, one update and one insert. The NULL values are present, because we do not have oldValues on insert neither newValues on Delete.
How do you generate this magic 🙂 ?
Pretty much, 45 lines of SQL are quite enough.
Here comes the code:
CREATE TABLE MoneyLogs
Id INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
ChangeDate DATETIME DEFAULT GETDATE() NOT NULL,
Command NCHAR(6) NOT NULL,
OldCell BIGINT NULL,
NewCell BIGINT NULL,
OldPaidPerCell BIGINT NULL,
NewPaidPerCell BIGINT NULL,
UserName NCHAR(100) NOT NULL
CREATE TRIGGER money_chess_change
AFTER INSERT, UPDATE, DELETE
DECLARE @operation CHAR(6)
SET @operation = CASE
WHEN EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted)
WHEN EXISTS(SELECT * FROM inserted)
WHEN EXISTS(SELECT * FROM deleted)
IF @operation = 'Delete'
INSERT INTO MoneyLogs (Command, ChangeDate, OldCell, OldPaidPerCell, UserName)
SELECT @operation, GETDATE(), d.Cell, d.PaidPerCell, USER_Name()
FROM deleted d
IF @operation = 'Insert'
INSERT INTO MoneyLogs (Command, ChangeDate, NewCell, NewPaidPerCell, UserName)
SELECT @operation, GETDATE(), i.Cell, i.PaidPerCell, USER_Name()
FROM inserted i
IF @operation = 'Update'
INSERT INTO MoneyLogs (Command, ChangeDate, NewCell, OldCell, NewPaidPerCell,OldPaidPerCell, UserName)
SELECT @operation, GETDATE(), d.Cell, i.Cell, d.PaidPerCell, i.PaidPerCell, USER_Name()
FROM deleted d, inserted i
Enjoy it! 😀