I have the trigger in one table and would like to read UserId value when a row is inserted, updated or deleted. How to do that? The code below does not work, I get error on UPDATED
ALTER TRIGGER [dbo].[UpdateUserCreditsLeft]
ON [dbo].[Order]
AFTER INSERT,UPDATE,DELETE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE
@UserId INT,
SELECT @UserId = INSERTED.UserId FROM INSERTED, DELETED
UPDATE dbo.[User] SET CreditsLeft = CreditsLeft - 1 WHERE Id = @UserId
END
Please note that
inserted, deletedmeans the same thing asinserted CROSS JOIN deletedand gives every combination of every row. I doubt this is what you want.Something like this may help get you started…
Depending on what you want to do, you then reference the table you are interested in with
inserted.userIDordeleted.userID, etc.Finally, be aware that
insertedanddeletedare tables and can (and do) contain more than one record.If you insert 10 records at once, the
insertedtable will contain ALL 10 records. The same applies to deletes and thedeletedtable. And both tables in the case of an update.EDIT Examplee Trigger after OPs edit.
If the PrimaryKey of
UpdateUserCreditsLeftis something other than UserID, use that in the FULL OUTER JOIN instead.