[英]SQL Server 2005 history tables using triggers
I have a table and want to insert the current values of records that are being updated or deleted. 我有一个表,想要插入要更新或删除的记录的当前值。
I tried to create a trigger on before update and on before delete but SQL Server 2005 doesn't like the before word. 我尝试在更新之前和删除之前创建触发器,但是SQL Server 2005不喜欢before词。
How do I get this to work? 我该如何工作?
I want the trigger to take the current record and copy it to a history table that is a mirror of the base table with the two added fields of dateBackedUp
(that takes a getDate()) and a field called action
(that takes the action 'updated' or deleted') 我希望触发器获取当前记录并将其复制到历史表,该历史表是基本表的镜像,其中添加了两个字段
dateBackedUp
(使用getDate())和一个称为action
的字段(使用action'已更新”或“已删除”)
please help 请帮忙
SQL Server doesn't have a concept of BEFORE INSERT
or BEFORE DELETE
. SQL Server没有
BEFORE INSERT
或BEFORE DELETE
的概念。 These kind of audit operations really don't need to be executed before the action, most of the time - so just use the AFTER INSERT
and AFTER UPDATE
triggers that you already have. 实际上,大多数时候实际上不需要在执行操作之前执行这些审计操作-因此只需使用已经具有的
AFTER INSERT
和AFTER UPDATE
触发器即可。
using the deleted table works as it gives me the data that will be updated.
使用已删除的表是可行的,因为它为我提供了将要更新的数据。 the inserted table provides the new values... not the ones i want to log.
插入的表格提供了新值...而不是我要记录的值。
When you do an AFTER UPDATE
trigger, the Inserted
pseudo-table contains the new values - and the Deleted
table contains the old values. 当您执行
AFTER UPDATE
触发器时, Inserted
伪表包含新值Deleted
表包含旧值。 So for the AFTER UPDATE
trigger, you can access both pseudo tables and get both the old and the new values. 因此,对于
AFTER UPDATE
触发器,您可以访问两个伪表并获取旧值和新值。
The AFTER INSERT
trigger only has access to Inserted
pseudo table which contains the values that were inserted. AFTER INSERT
触发器只能访问包含已插入值的Inserted
伪表。
The AFTER DELETE
trigger only has access to the Deleted
pseudo table which contains the values of the rows that were deleted. AFTER DELETE
触发器只能访问Deleted
伪表,该表包含Deleted
的行的值。
You don't need to use a before
keyword. 您不需要使用
before
关键字。 You can create a trigger as normal and then select from the deleted
table which gets created when a trigger is..er...triggered. 您可以正常创建触发器,然后从
deleted
表中进行选择,该触发器是在触发触发器时创建的。
eg 例如
create trigger Audit
on tblCustomers
after update, delete
insert into tblAudit
select * from deleted;
(untested as I don't have a SQL Server here, but if doesn't work then the BOL entry for Create Trigger
should tell you about the deleted
table) (请耐心等待,因为我在这里没有SQL Server,但如果无法使用,则
Create Trigger
的BOL条目应告诉您有关deleted
表的信息)
create TRIGGER [update_Project] ON Project
FOR UPDATE
AS
INSERT project_history
SELECT * FROM deleted
using the deleted table works as it gives me the data that will be updated. 使用已删除的表是可行的,因为它为我提供了将要更新的数据。 the inserted table provides the new values... not the ones i want to log.
插入的表格提供了新值...而不是我要记录的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.