1

我有以下 SQL 触发器:

ALTER TRIGGER [dbo].[DIENSTLEISTUNG_Update]
ON [dbo].[DIENSTLEISTUNG]
INSTEAD OF UPDATE
AS
BEGIN

SET  NOCOUNT ON;


        INSERT INTO [DIENSTLEISTUNG] 
                 (DESCRIPTION, QUANTITY, 
                  PRICE, AZ_MO, AZ_DI,AZ_MI,AZ_DO,AZ_FR,
                  AZ_SA,AZ_SO,DIENSTLEISTUNGSART_ID,
                  UPDATE_USER, UPDATE_DATE,
                  PERMISSIONS, KONTRAKTPOSITION,ITEMNUMBER,
                  PRIORITY, VALID)
        SELECT  DESCRIPTION, QUANTITY, PRICE AZ_MO, AZ_DI,AZ_MI,AZ_DO,AZ_FR,
                AZ_SA,AZ_SO,SERVICETYPE_ID, UPDATE_USER,GETDATE(),
                PERMISSIONS, KONTRAKTPOSITION,ITEMNUMBER, PRIORITY, 'Y',VALID
        FROM INSERTED

        UPDATE  SERVICE
        SET  VALID = 'N' 
        FROM    SERVICE
                INNER JOIN INSERTED ON INSERTED.ID = SERVICE.ID



SET  NOCOUNT OFF;      
END

如果原始行发生更改,触发器会复制具有新 ID 的整行。到现在为止还挺好。我希望触发器仅在更新PRICEDESCRIPTION更新时创建一个新行。如果我对PRIORITYorITEMNUMER或其他列进行更新,则触发器应该只更新行,而不是创建新行。

我怎样才能做到这一点?

4

2 回答 2

1

您可以使用 INSERTED 和 DELETED 表:

INSERT INTO [DIENSTLEISTUNG] 
         (DESCRIPTION, QUANTITY, 
          PRICE, AZ_MO, AZ_DI,AZ_MI,AZ_DO,AZ_FR,
          AZ_SA,AZ_SO,DIENSTLEISTUNGSART_ID,
          UPDATE_USER, UPDATE_DATE,
          PERMISSIONS, KONTRAKTPOSITION,ITEMNUMBER,
          PRIORITY, VALID)
SELECT  i.DESCRIPTION, i.QUANTITY, i.PRICE, i.AZ_MO, i.AZ_DI,i.AZ_MI,i.AZ_DO,i.AZ_FR,
        i.AZ_SA,i.AZ_SO,i.SERVICETYPE_ID, i.UPDATE_USER,GETDATE(),
        i.PERMISSIONS, i.KONTRAKTPOSITION,i.ITEMNUMBER, i.PRIORITY, 'Y',i.VALID
FROM INSERTED i
     JOIN deleted d ON i.ID=d.ID
WHERE i.PRICE<>d.PRICE
      or i.DESCRIPTION<>d.DESCRIPTION

    UPDATE  S
    SET  s.VALID = 'N',
         s.priority=i.priority,
         s.QUANTITY =i.QUANTITY,
         ...  
    FROM    SERVICE s
            JOIN INSERTED i ON I.ID = S.ID
            JOIN deleted d ON i.ID=d.ID
    WHERE i.PRICE=d.PRICE
          or i.DESCRIPTION=d.DESCRIPTION
于 2012-07-27T07:29:46.903 回答
0

您需要检查 COLUMNS_UPDATED 属性。结果值取决于表的结构。

http://msdn.microsoft.com/en-us/library/ms186329.aspx

或者您可以比较删除表和插入表中的值。

于 2012-07-27T07:19:33.780 回答