I am trying to use an update trigger in SQL Server 2000 so that when an update occurs, I insert a row into a history table, so I retain all history on a table:
CREATE Trigger trUpdate_MyTable ON MyTable
FOR UPDATE
AS
INSERT INTO
[MyTableHistory]
(
[AuditType]
,[MyTable_ID]
,[Inserted]
,[LastUpdated]
,[LastUpdatedBy]
,[Vendor_ID]
,[FromLocation]
,[FromUnit]
,[FromAddress]
,[FromCity]
,[FromProvince]
,[FromContactNumber]
,[Comment])
SELECT
[AuditType] = 'U',
D.*
FROM
deleted D
JOIN
inserted I ON I.[ID] = D.[ID]
GO
Of course, I get an error
Cannot use text, ntext, or image columns in the ‘inserted’ and ‘deleted’ tables.
I tried joining to MyTable instead of deleted, but because the insert trigger fires after the insert, it ends up inserting the new record into the history table, when I want the original record.
How can I do this and still use text columns?
the only way to do this is keep the current row in the history table too. Do what you tried and join to the actual table, and insert all columns from current actual table into the history table.
you probably have something like this, where the history only has the previous version of a row:
I’m saying do something like this, where every version is stored:
this way whenever there is an insert or update, just insert the current row into the history table, you have a duplicate of the current row, but that isn’t that terrible.
If you are just adding this trigger to an existing table with data in it, then run a query like this to prepopulate all the current values for you: