如何组合触发器

时间:2014-04-26 07:56:25

标签: sql sql-server-2008 triggers

SQL新手寻求帮助。

我正在使用SQL Server 2008。

目前我有2个触发器,它们都与同一个表有关。

是否可以将这两个触发器结合起来,或者将它们分开是更好的做法吗?

ALTER TRIGGER PingtreeNode2_IU_Trig
ON dbo.PingtreeNode
FOR INSERT, UPDATE
AS
IF NOT EXISTS (
                SELECT
                        pt.ID
                    FROM
                        PingtreeTier pt
                    INNER JOIN
                        inserted i ON
                            pt.ID = i.PingtreeTierID
                    INNER JOIN
                        Product p ON
                            i.ProductID = p.ID
                    WHERE
                        pt.ProductServiceTypeID = p.ServiceTypeID
                )
BEGIN
    ROLLBACK TRANSACTION
END

ALTER TRIGGER PingtreeNode_IU_Trig
ON dbo.PingtreeNode
FOR INSERT, UPDATE
AS
IF NOT EXISTS (
                SELECT
                        pt.ID
                    FROM
                        Pingtree pt
                    INNER JOIN
                        PingtreeTier pt2 ON
                            pt.ID = pt2.PingtreeID
                    INNER JOIN
                        inserted i ON
                            pt2.ID = i.PingtreeTierID
                    INNER JOIN
                        Product p ON
                            i.ProductID = p.ID
                    WHERE
                        pt.ProductTypeID = p.TypeID
                )
BEGIN
    ROLLBACK TRANSACTION
END

1 个答案:

答案 0 :(得分:2)

ALTER TRIGGER PingtreeNode2_IU_Trig_Combined
ON dbo.PingtreeNode
FOR INSERT, UPDATE
AS
BEGIN
  SET NOCOUNT ON;
IF(   
   (
   NOT EXISTS (
               SELECT pt.ID
               FROM PingtreeTier pt INNER JOIN inserted i 
               ON   pt.ID = i.PingtreeTierID
               INNER JOIN Product p 
               ON i.ProductID = p.ID
               WHERE pt.ProductServiceTypeID = p.ServiceTypeID 
               ) 
    )          
   OR 
    (
   NOT EXISTS (
                SELECT pt.ID
                FROM Pingtree pt INNER JOIN PingtreeTier pt2 
                ON pt.ID = pt2.PingtreeID
                INNER JOIN inserted i 
                ON  pt2.ID = i.PingtreeTierID
                INNER JOIN Product p 
                ON i.ProductID = p.ID
                WHERE  pt.ProductTypeID = p.TypeID
                )
     )
  )

    BEGIN
        ROLLBACK TRANSACTION
    END
END