我的更新触发器有问题
ALTER TRIGGER tr_MyTable
ON MyTable
AFTER UPDATE
AS
BEGIN TRAN
SET NOCOUNT ON;
If Update(column)
Begin
DELETE FROM MyTable WHERE <condition>
End
SET NOCOUNT OFF
COMMIT TRAN
GO
我正在尝试删除当前在MyTable中已更新的行(来自MayTable)。但是当我运行触发器时,该行不会被删除。是否无法删除当前在更新触发器内更新的行? (删除和更新在同一个表中)
谢谢!
编辑:
ALTER TRIGGER tr_MyTable
ON MyTable
AFTER UPDATE
AS
BEGIN TRAN
SET NOCOUNT ON;
SELECT @ID = ID
FROM inserted
If Update(column)
Begin
DELETE FROM MyTable WHERE ID = @ID
End
SET NOCOUNT OFF
COMMIT TRAN
GO
编辑2:
ALTER PROCEDURE sp_Update
(
@ID INTEGER,)
AS
SET NOCOUNT ON
Begin Tran
Update MyTable SET Column = Data where ID = @ID
Commit Tran
SET NOCOUNT OFF
GO
此更新程序正在运行,列已更新。触发器也被触发,并且执行delete(print语句)而不执行delete语句。 但是当我直接在表中更新列时,没有形成prosedure触发器触发并且删除语句正常工作。我不使用回滚。
答案 0 :(得分:2)
你是如何删除的??
您应该从INSERTED和DELETED表中读取您的值,例如:
DELETE FROM MyTable WHERE id in (select ID from INSERTED)
答案 1 :(得分:2)
也许您想在INSTEAD OF触发器中执行此操作。如果有人尝试更新该列,您可以删除该行,否则您将重新执行更新。这里唯一的挑战是你必须在触发器中重新编写update语句。 (此外,您在触发器内部并不需要额外的BEGIN TRAN / COMMIT TRAN。)
CREATE TRIGGER dbo.tr2_myTable
ON dbo.MyTable
INSTEAD OF UPDATE
AS
BEGIN
SET NOCOUNT ON;
-- update the rows where the column hasn't changed
UPDATE s
SET col1 = i.col1, col2 = i.col2, ...
FROM dbo.MyTable AS s
INNER JOIN inserted AS i
ON s.key = i.key
INNER JOIN deleted AS d
ON i.key = d.key
AND i.column_that_should_not_change = d.column_that_should_not_change;
-- delete the rows where the column HAS changed
-- (note that this requirement sounds odd to me)
DELETE s
FROM dbo.MyTable AS s
INNER JOIN inserted AS i
ON s.key = i.key
INNER JOIN deleted AS d
ON i.key = d.key
AND i.column_that_should_not_change <> d.column_that_should_not_change;
END
GO
请注意,与IF UPDATE()
逻辑不同,此触发器实际上会处理多个行(例如,某些列已更改的位置,以及某些位置未更改的位)。另请注意,即使有人说IF UPDATE(x)
,UPDATE foo SET x = x;
也会成立。
这假设您有一个键列,并且column_that_should_not_change不可为空。如果此列允许NULL,则逻辑会变得更复杂。
答案 2 :(得分:1)
有可能。
如果您愿意,可以在触发器中设置DELETE FROM MyTable
,这应该可行。您是否已经过测试以确认正在执行触发器并且您的代码已到达DELETE FROM MyTable WHERE <condition>
行?