代码之家  ›  专栏  ›  技术社区  ›  schar

条件更新存储过程总是触发触发器

  •  0
  • schar  · 技术社区  · 15 年前

    我有一个存储过程

    update table1 set value1 = 1 where value1 = 0 and date < getdate() 
    

    我有一个触发器

    CREATE TRIGGER NAME ON TABLENAME
    FOR UPDATE
    ...
    if UPDATE(value1) 
    BEGIN
    --Some code to figure out that this trigger has been called
    -- the value is always null
    END
    

    知道为什么即使存储过程不更新任何值也会调用此触发器吗?

    2 回复  |  直到 15 年前
        1
  •  3
  •   KSimons    15 年前

    阅读有关update()的联机丛书文章,这实际上是一本不错的书。 你可以在这里找到它, http://msdn.microsoft.com/en-us/library/ms187326.aspx .

    回答: 如果列是“updated”,update()将返回true,即使没有行受到更新的影响。

    例如(设置):

    If OBJECT_ID('TestTrigger', 'U') is not null drop table TestTrigger
    GO
    create table TestTrigger(
      ID int identity(1,1)
    , Col1 int
    , Col2 int
    , Trig varchar(1) default 'N' 
    )
    Insert into TestTrigger(Col1, Col2) values (1,1)
    Insert into TestTrigger(Col1, Col2) values (1,2)
    GO
    IF OBJECT_ID('Testing', 'TR') is not null drop trigger Testing
    GO
    Create Trigger Testing on TestTrigger
    For Update
    as
    Begin
    If Update(Col1)
        begin
            Update TestTrigger Set Trig='Y' where ID=(Select ID from Inserted)
        end
    End 
    

    如果我跑 Update TestTrigger Set Col1=0 where Col2=1 检查一下我的行踪

    (1 row(s) affected)
    (1 row(s) affected)
    

    我们知道这是真的,1受update语句的影响,另一个受触发器的影响。 如果我跑 Update TestTrigger Set Col1=0 where Col2=10 我会明白的,

    (0 row(s) affected)
    (0 row(s) affected)
    

    这意味着update(col1)返回为true(因为否则我们只返回受影响的一行)。

    如果我跑 Update TestTrigger Set Col2=0 where Col2=10 我会看到的

    (0 row(s) affected)
    

    这是因为col1不再被引用。正如@schar提到的,检查@rowcount也是一个好主意,或者您也可以像我一样使用(插入链接)。

    克里斯

    编辑:和添加,从create trigger bo文章( http://msdn.microsoft.com/en-us/library/ms189799.aspx )

    当任何有效的 无论是否 或者不影响任何表行。

        2
  •  0
  •   schar    15 年前

    一位朋友评论说,我会很好地使用触发器中的以下行(指示触发器总是触发)

    IF @@ROWCOUNT=0 RETURN