如果更新了特定列,则仅创建新行

时间:2012-07-27 07:13:47

标签: sql sql-server sql-server-2008

我有以下SQL-Trigger:

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

如果原始行发生更改,Trigger会使用新ID复制整行。 到现在为止还挺好。我希望触发器只在PRICEDESCRIPTION更新时才创建新行。如果我在PRIORITYITEMNUMER或其他列上执行更新,则触发器应仅更新行,但不会创建新行。

我该怎么做?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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

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