使用条件而不是触发器

时间:2015-07-31 04:29:24

标签: sql sql-server triggers

我创建了一个而不是在用户更新内容时触发的更新触发器。但我想知道添加条件。我希望仅当visiblity列值更改为publish时才触发触发器。我有两个访问级别条目和质量控制。

CREATE TRIGGER ProjUpdTrig 
   ON  Projects 
   INSTEAD OF UPDATE
AS 
BEGIN
    declare @ProjId int
    declare @ProjCode varchar(100) 
    declare @ProjTitle varchar(150) 
    declare @ProjDetails varchar(MAX)
    declare @ProgramId int 
    declare @CategId int
    declare @ProvinceId int 
    declare @FinalCost varchar(50) 
    declare @ProjStartDate date 
    declare @ProjEndDate date 
    declare @PercentCompleted varchar(3) 
    declare @ProjStatus varchar(30)
    declare @StatusReportvarchar(Max) 
    declare @Visibility varchar(100) 
    declare @UpdUserId int   
    select @ProjId=ProjId,@ProjCode=ProjCode,@ProjTitle=ProjTitle,@ProjDetails=ProjDetails,@ProgramId=ProgramId,@CategId=CategId,@ProvinceId=ProvinceId,@FinalCost=FinalCost,@ProjStartDate=ProjStartDate,@ProjEndDate=ProjEndDate,@PercentCompleted=PercentCompleted,@ProjStatus=ProjStatus,@StatusReport=StatusReport,@Visibility=Visibility,@UpdUserId=UpdUserId from deleted 
    INSERT INTO ProjAudit (ProjId,ProjCode,ProjTitle,ProjDetails,ProgramId,CategId,ProvinceId,FinalCost,
ProjStartDate,ProjEndDate,PercentCompleted,ProjStatus,
StatusReport,Visibility,UpdUserId)
VALUES
(@ProjId,@ProjCode,@ProjTitle,@ProjDetails,@ProgramId,@CategId,@ProvinceId,
@AgencyId,@FinalCost,@ProjStartDate@ProjEndDate,@PercentCompleted,
@ProjStatus,@StatusReport,@Visibility,@UpdUserId)
END
GO

问题:如果可见性更改为发布,如何触发触发器,因为QC用户有权更改可见性?我不希望跟踪用户活动。我使用过Where,但对我不起作用。

我已将代码更新为:

CREATE TRIGGER ProjUpdTrig 
ON  Projects 
INSTEAD OF UPDATE
AS 
BEGIN
    INSERT INTO ProjAudit (ProjId, ProjCode, ProjTitle, ProjDetails, 
                           ProgramId, CategId, ProvinceId, FinalCost, 
                           ProjStartDate, ProjEndDate, PercentCompleted, 
                           ProjStatus, StatusReport, Visibility, UpdUserId)
       SELECT 
          ProjId, ProjCode, ProjTitle, ProjDetails, 
          ProgramId, CategId, ProvinceId, FinalCost, 
          ProjStartDate, ProjEndDate, PercentCompleted, 
          ProjStatus, StatusReport, Visibility, UpdUserId
       FROM deleted del 
       JOIN inserted ins ON del.projid = ins.projid
       WHERE 
           ins.VisibilityByMin <> del.VisibilityByMin
END
GO

但现在我收到了错误:

  

消息102,级别15,状态1,过程ProjUpdTrig,第10行“可见性”附近的语法不正确

1 个答案:

答案 0 :(得分:0)

触发器无论如何都会触发,但你能做的是:

INSERT INTO ProjAudit <cols>
SELECT <cols> 
FROM deleted del 
    JOIN inserted ins ON del.projid = ins.projid
WHERE ins.Visibility <> del.Visibility

这样它只会插入你所追求的行。您不需要首先将它们声明为变量