基本SQL更新触发器

时间:2012-04-13 08:15:48

标签: sql tsql

我想创建一个在更新表中的行之前运行的触发器,并在将行更新到存档表之前写入该行中的所有字段。在更新之前访问行字段所需的正确语法是什么,以便我可以将它们写入我的归档表?

编辑:

所以这应该做我想要的,但它似乎不起作用。我收到错误'数据库中已经有一个名为config_SystemSettings的对象:

CREATE TRIGGER [config].[UpdateSystemSettings]

ON [config]。[系统设置]    更新后 如 BEGIN

SET NOCOUNT ON;

SELECT old.settingId, old.campId, old.settingKey, old.settingValue
into [history].[config_SystemSettings]
FROM [config].[SystemSetting] AS old
INNER JOIN deleted AS del ON del.settingId = old.settingId

END GO

1 个答案:

答案 0 :(得分:0)

SELECT ... INTO总是想要创建一个新表 - 所以请改用INSERT ... SELECT

CREATE TRIGGER [config].[UpdateSystemSettings]

ON [config].[SystemSetting] AFTER UPDATE AS BEGIN
SET NOCOUNT ON;

insert into [history].[config_SystemSettings] (settingId,campId,settingKey,settingValue)
SELECT old.settingId, old.campId, old.settingKey, old.settingValue
FROM [config].[SystemSetting] AS old
INNER JOIN deleted AS del ON del.settingId = old.settingId

但您必须先明确创建[history].[config_SystemSettings]