views:

82

answers:

3

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

+1  A: 

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.

marc_s
stil bad programming technique for a trigger, never assume only one record will be in inserted or deleted.
HLGEM
@HLGEM: totally agree- I didn't write this code either - I just tried to illustrate to the OP how to use the "Deleted" table instead of "Inserted" - that's all
marc_s
+2  A: 

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
Robin Day
A: 

The records that were updated are in the DELETED virtual table, not INSERTED. Change "from inserted" to "from deleted" and that should work.

Cody C