1

我执行以下触发器:

ALTER TRIGGER [dbo].[TestTrigger] ON [dbo].[TestTable] 
after update as
    Declare @Name As varchar(30)
    update TestTable set [Name] = 'Rob Stanfield'
    select @Name = [Name] from inserted
    print @Name
GO

我正在执行的插入语句是:

INSERT INTO TestTable (name) VALUES ('Ed Watkins')

输出如下:

(1 row(s) affected)
Ed Watkins
(1 row(s) affected)

我希望输出是:

(1 row(s) affected)
Rob Stanfield

(1 row(s) affected)

我错过了什么?

4

1 回答 1

3

Inserted将是TestTable触发器运行之前更改的行的副本,因此其中 name 的值仍然是 Ed Watkins。

我不确定您为什么要这样做,但您必须查询刚刚更新的表才能在触发器中获取刚刚更新的新值:

ALTER TRIGGER [dbo].[TestTrigger] ON [dbo].[TestTable] 
after update as
    Declare @Name As varchar(30)
    update TestTable set [Name] = 'Rob Stanfield'
    select @Name = [Name] from TestTable 
    print @Name
GO

你真的在寻找instead of insert触发器吗?

于 2012-10-03T13:39:57.697 回答