1

我想在SELECT执行删除查询时使用触发器从 a 中删除所有行,而不删除最后返回的行。

此触发器不起作用,因此非常感谢任何帮助。

CREATE TRIGGER TR_StergereOfertaSpeciala
ON OferteSpeciale
INSTEAD OF DELETE
AS
DECLARE @nr INTEGER;

IF (EXISTS(SELECT * FROM DELETED))
BEGIN
SET @nr = (SELECT COUNT(*) FROM DELETED); 

DELETE FROM (   
SELECT TOP(@nr - 1)* FROM OferteSpeciale
INNER JOIN DELETED ON OferteSpeciale.codP = Deleted.codP 
    AND OferteSpeciale.codM = Deleted.codM 
    AND OferteSpeciale.dela = Deleted.dela)

END
4

1 回答 1

5

这是让您的概念正常工作的示例:

CREATE TRIGGER TR_StergereOfertaSpeciala
ON OferteSpeciale
INSTEAD OF DELETE
AS BEGIN
    DECLARE @nr INT
    SET @nr = (SELECT COUNT(*) FROM DELETED)
    IF (@nr > 1) BEGIN
        DELETE o
        FROM OferteSpeciale AS o
            INNER JOIN (SELECT TOP (@nr - 1) * FROM DELETED /* ORDER BY ??? */) AS d
                ON o.codP = d.codP 
                AND o.codM = d.codM 
                AND o.dela = d.dela
    END
END

请注意使用连接删除的语法。另请注意,我们任意选择要保留的 1 行。我会建议,正如@RBarryYoung 所提到的,专门通过一些东西来订购集合以了解我们保留哪一行。

另一种可以避免有些动态TOP子句(聪明,顺便说一句)的方法是专门排除您要继续使用的记录NOT EXISTS/IN

此外,在这种情况下,您可能希望避免触发器递归嵌套触发器。

于 2013-05-06T15:41:13.297 回答