简体   繁体   中英

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.

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.

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.

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:

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.

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. Change "from inserted" to "from deleted" and that should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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