Reputation: 678
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
Upvotes: 0
Views: 1318
Reputation: 754220
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.
Upvotes: 1
Reputation: 4797
The records that were updated are in the DELETED virtual table, not INSERTED. Change "from inserted" to "from deleted" and that should work.
Upvotes: 0
Reputation: 102458
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
Upvotes: 2