2

I want to copy the contents of a column into another column in the same table. Therefore, I created this trigger:

ALTER TRIGGER [dbo].[kennscht_copy_to_prodverpt]
ON [dbo].[Stammdaten]
AFTER INSERT
AS
UPDATE Stammdaten
SET PRODVERPT = (SELECT KENNSCHT FROM INSERTED)
WHERE SNR = (SELECT SNR FROM INSERTED);

But when I use an UPDATE on the table to update KENNSCHT to a different value, PRODVERPT is not updated as well. Now, you could argue that is because the trigger is on AFTER INSERT and not AFTER UPDATE, but when I change it so it's triggered by UPDATE and INSERT, whenever I update any row, I get an error message from SQL Server

Cannot update row because it would make the row not unique or update multiple rows (2 rows) [sic]

What is going on here? Either the trigger doesn't do anything, or it's messing up the whole table, making it un-updateable.

Update: I also tried the following trigger:

UPDATE s
SET s.PRODVERPT = i.KENNSCHT
FROM Stammdaten s
INNER JOIN INSERTED i ON i.SNR = s.SNR;

But it has exactly the same behaviour. If I use only AFTER INSERT, nothing changes and if I use AFTER INSERT, UPDATE I get the error message above.

Update 2: There are no multiple rows in the table, I already checked that because I thought it might be connected to the issue.

4

1 回答 1

3

如果将此触发器作为AFTER UPDATE触发器运行,它将递归运行,因为它总是针对同一个表发出另一个 UPDATE 语句,这会导致触发器的另一个执行。

要解决此问题,您要么需要使更新触发器成为INSTEAD OF UPDATE触发器,要么测试KENNSCHT列是否被修改。对于后者,您可以使用如下UPDATE()函数:

ALTER TRIGGER [dbo].[kennscht_copy_to_prodverpt_after_update]
ON [dbo].[Stammdaten]
AFTER UPDATE
AS
BEGIN
    SET NOCOUNT ON
    IF (UPDATE(KENNSCHT))
    BEGIN
        UPDATE s
            SET s.PRODVERPT = i.KENNSCHT
            FROM Stammdaten s
            INNER JOIN INSERTED i ON i.SNR = s.SNR
    END
END
于 2013-09-10T09:59:53.237 回答