SQL Trigger被多次调用

时间:2015-04-28 20:27:51

标签: sql sql-server triggers

我有一个INSERT TRIGGER如下:

ALTER TRIGGER [dbo].[TrackingInitialize]
   ON  [dbo].[WorkSchedule_] 
   AFTER INSERT
AS
    DECLARE @work_area varchar(255);
    DECLARE @schedule_date date;
    DECLARE @employee1 varchar(255);
    DECLARE @hours1 float;

BEGIN

    SET NOCOUNT ON;

    SELECT @work_area=i.WorkArea FROM inserted i;
    SELECT @schedule_date=i.ScheduleDate FROM inserted i;
    SELECT @employee1=i.Employee1 FROM inserted i;
    SELECT @hours1=i.Hours1 FROM inserted i;

    SELECT @ccname = CostCenter_.Name
    FROM WorkArea_, CostCenter_
    WHERE WorkArea_.CostCenterID = CostCenter_.ID and WorkArea_.WorkAreaName = @work_area

    IF (@employee1 is not NULL)
    BEGIN   
        INSERT into dbo.TrackingInfo_ VALUES(@schedule_date, @employee1, @work_area,null,null,null,null,null, null, null,@ccname,null, @hours1, 0.0, @hours1,0.0);
    END
END

我在我的asp.net应用程序中使用cmd.ExecuteScalar()INSERT个新值。但是每次插入后,我的触发器都会插入额外的7行数据,其中employee为null。任何循环内都不存在查询执行。怎么可能?

2 个答案:

答案 0 :(得分:4)

我不确定触发器的问题是什么,但是没有正确编程。您假设inserted只包含一行,这是不正确的。

也许您希望触发器执行此操作:

    INSERT into dbo.TrackingInfo_
        SELECT employee, work_area, null, null, null ,null, null, null, null,
               cc.name, null, hours, 0.0, hours1, 0.0
        FROM inserted i JOIN
             WorkArea_ w 
             ON w.workareaname = i.work_area JOIN
             CostCenter_ cc
             ON w.CostCenterID = cc.ID 
        WHERE employee IS NOT NULL;

我强烈建议您在insert中明确列出列。

答案 1 :(得分:0)

问题是触发器的if语句失败,因为员工值被分配为空而非空。所以更改了TRIGGER代码如下:

 IF (@employee1 is not NULL AND datalength(@employee1) != 0)
    BEGIN   
        INSERT into dbo.TrackingInfo_ SELECT employee, work_area, null, null, null ,null, null, null, null,
           cc.name, null, hours, 0.0, hours1, 0.0
    FROM inserted i JOIN
         WorkArea_ w 
         ON w.workareaname = i.work_area JOIN
         CostCenter_ cc
         ON w.CostCenterID = cc.ID 
    WHERE employee IS NOT NULL;
    END

现在工作正常。谢谢你们:))