SQL触发器不更新所有插入的行

时间:2017-03-19 17:52:46

标签: sql-server triggers sql-insert

SQL Trigger没有更新所有插入的行,只有几行得到更新,我无法理解原因。行正在获取行ID和RateID,我已通过在审核日志中创建rowId条目来测试触发器

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[mytrigger]
   ON  [dbo].[myTable]
   AFTER INSERT
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

     DECLARE    @RowId int,
                @RateID int,
                @RateCode NVARCHAR(50)

 SELECT @RateID = RateID,             
            @RowId = RowId
     FROM inserted

    // Method I found on StackOverflow
    --   Update cr
    --   Set cr.RateCode = r.RateCode
    --   From mytable cr
    --   inner join inserted on cr.RowId = inserted.RowId
    --   inner join rates r on inserted.RateID = r.ID
       --where cr.RowId = inserted.RowId

      //Method Aaron Suggested
--UPDATE t1
  --SET t1.RateCode = t2.RateCode
  --FROM dbo.mytable AS t1
 -- INNER JOIN dbo.rates AS t2
 -- ON t1.RateID = t2.ID
 -- WHERE t1.RowId = inserted.RowId

    // Method I am currently using
     IF @RateID IS NOT NULL
     BEGIN
      Select @RateCode = RateCode From rates where ID = @RateID
       IF @RateCode IS NOT NULL      
         Update mytable Set RateCode = @RateCode Where RowId = @RowId
            --UPDATE [dbo].[mytable ] SET  RateCode = @RateCode FROM Inserted i WHERE mytable .RowId = i.RowId
     END
END

0 个答案:

没有答案