简体   繁体   English

SQL Server 2005触发器

[英]SQL Server 2005 triggers

I created a trigger on a table for updates. 我在表上创建了一个触发器以进行更新。 If any update happens, I want to store the old value in separate table. 如果发生任何更新,我想将旧值存储在单独的表中。 I am trying to get the old value from "inserted" table, but this table is not populated with old values after update. 我正在尝试从“插入”表中获取旧值,但是更新后此表未填充旧值。

Here is the sample code: 这是示例代码:

CREATE TRIGGER [dbo].[Logs_Update]
   ON  [dbo].[Logs] AFTER  UPDATE
AS 

 DECLARE @url varchar(50)

BEGIN

 SELECT @url =  i.url 
   FROM INSERTED i

 INSERT INTO dbo.Triggers_tbl
   (ID, URL) 
 VALUES
   (1000, @url)

END

I get @url as null from the inserted table. 我从插入的表中获取@url为null。

Please let me know what is wrong with the trigger 请让我知道扳机有什么问题

The DELETED table contains the "old" values and the "INSERTED" table contains the "new" values. DELETED表包含“旧”值,而“ INSERTED”表包含“新”值。

To add to this, the INSERTED and DELETED tables may contain multiple rows if your update affects multiple rows and therefore you should probably run your insert with an INSERT SELECT rather than a variable. 除此之外,如果您的更新影响多行,则INSERTED和DELETED表可能包含多行,因此,您可能应该使用INSERT SELECT而不是变量来运行插入。

INSERT INTO dbo.Triggers_tbl(URL) SELECT d.url FROM DELETED d

The "old" values (after an UPDATE ) are available in the Deleted pseudo-table: “旧”值(在UPDATE )在Deleted伪表中可用:

CREATE TRIGGER [dbo].[Logs_Update]
   ON  [dbo].[Logs]
   AFTER  UPDATE
AS 
   DECLARE @url varchar(50)

   SELECT @url =  d.url from deleted d

   INSERT INTO dbo.Triggers_tbl(ID,URL) VALUES(1000,@url)

As HLGEM correctly commented on, the OP's code is assuming the trigger will be called for each row separately - which is not correct. 正如HLGEM正确评论的那样,OP的代码假定将分别为每一行调用触发器-这是不正确的。

In that light, the trigger code really ought to deal with a set of rows being updated, and thus it should be something like: 鉴于此,触发代码确实应该处理一正在更新的行 ,因此它应该类似于:

CREATE TRIGGER [dbo].[Logs_Update]
   ON  [dbo].[Logs]
   AFTER  UPDATE
AS 
   INSERT INTO dbo.Triggers_tbl(ID,URL) 
      SELECT 1000, d.url
      FROM Deleted d

or something like that. 或类似的东西。

The records that were updated are in the DELETED virtual table, not INSERTED. 更新的记录在DELETED虚拟表中,而不是INSERTED。 Change "from inserted" to "from deleted" and that should work. 将“从插入”更改为“从已删除”,这应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM