FIM - SQL用于更新Delta表中记录的触发器

时间:2015-06-11 10:40:49

标签: sql triggers dml

我在一个表(主表)中发生更改(更新或插入)时编写DML触发器,我想将整行写入另一个表(Delta表)。 Master和Delta表包含具有相同数据类型的相同列,但Delta表包含一个名为' change_type'的附加列,它应该表示' INSERT'或者修改',具体取决于更新增量表的触发器。

我遇到的困难是我想使用插入的表来更新Delta表行,但它给了我错误。

CREATE TRIGGER [dbo].[TR_Update] 
   ON  [dbo].[People_Master]
   AFTER Update
AS 
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

Declare @RowCount int
Declare @ID int
Declare @Email nvarchar(50)
Declare @ct nvarchar(10)

select @ID = ID from inserted


Select @RowCount=COUNT(*) from People_Delta where People_Delta.ID = @ID and People_Delta.change_type = 'Modify';

if(@RowCount = 0)
Begin
    Insert into People_Delta (ID,Email,uac,Department,FirstName,change_type)
    values (iserted.ID,inserted.Email,inserted.uac,inserted.Department,inserted.Firstname'Modify');
END

END
GO

我的表有5列。

ID (primary key)
Email
Firstname
uac
Department

1 个答案:

答案 0 :(得分:0)

您在,声明中遗漏了INSERT

由于您指定的列数与您要插入的值的数量不匹配,因此会出错。

  

inserted.Firstname '修改'

Insert into People_Delta (ID,Email,uac,Department,FirstName,change_type)
    values (iserted.ID,inserted.Email,inserted.uac,inserted.Department,inserted.Firstname,'Modify');