如何删除所有行而不删除SQL Server中最后返回的行?

时间:2013-05-06 15:18:42

标签: sql sql-server tsql triggers

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

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

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

1 个答案:

答案 0 :(得分: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子句(聪明,BTW)的方法是使用NOT EXISTS/IN

专门排除你想要保留的记录

另外,在这种情况下,您可能希望避免使用trigger recursionnested triggers