Please note that inserted, deleted
means the same thing as inserted CROSS JOIN deleted
and gives every combination of every row. I doubt this is what you want.
Something like this may help get you started...
SELECT
CASE WHEN inserted.primaryKey IS NULL THEN 'This is a delete'
WHEN deleted.primaryKey IS NULL THEN 'This is an insert'
ELSE 'This is an update'
END as Action,
*
FROM
inserted
FULL OUTER JOIN
deleted
ON inserted.primaryKey = deleted.primaryKey
Depending on what you want to do, you then reference the table you are interested in with inserted.userID
or deleted.userID
, etc.
Finally, be aware that inserted
and deleted
are tables and can (and do) contain more than one record.
If you insert 10 records at once, the inserted
table will contain ALL 10 records. The same applies to deletes and the deleted
table. And both tables in the case of an update.
EDIT Examplee Trigger after OPs edit.
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;
UPDATE
User
SET
CreditsLeft = CASE WHEN inserted.UserID IS NULL THEN <new value for a DELETE>
WHEN deleted.UserID IS NULL THEN <new value for an INSERT>
ELSE <new value for an UPDATE>
END
FROM
User
INNER JOIN
(
inserted
FULL OUTER JOIN
deleted
ON inserted.UserID = deleted.UserID -- This assumes UserID is the PK on UpdateUserCreditsLeft
)
ON User.UserID = COALESCE(inserted.UserID, deleted.UserID)
END
If the PrimaryKey of UpdateUserCreditsLeft
is something other than UserID, use that in the FULL OUTER JOIN instead.