gpt4 book ai didi

SQL Server : trigger how to read value for Insert, 更新、删除

转载 作者:行者123 更新时间:2023-12-02 04:31:21 25 4
gpt4 key购买 nike

我在一个表中有触发器,并且希望在插入、更新或删除行时读取 UserId 值。怎么做?下面的代码不起作用,我在 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

最佳答案

请注意,插入、删除插入CROSS JOIN删除含义相同,并给出每行的每种组合。我怀疑这就是你想要的。

这样的事情可能会帮助您开始......

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


根据您想要执行的操作,然后使用 inserted.userIDdeleted.userID 等引用您感兴趣的表。


最后,请注意,inserteddeleted,并且可以(并且确实)包含多个记录。

如果您一次插入 10 条记录,inserted 表将包含所有 10 条记录。这同样适用于删除和 deleted 表。以及更新情况下的两个表。


编辑示例 OP 编辑​​后触发。

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


如果 UpdateUserCreditsLeft 的 PrimaryKey 不是 UserID,请在 FULL OUTER JOIN 中使用它。

关于SQL Server : trigger how to read value for Insert, 更新、删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8505924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com