IF EXISTS(SELECT * FROM sysobjects O, sysusers U
          WHERE
            o.name = 'DTULTATU_PRODMODFILI'  and
            type = 'TR'               and
            u.uid = o.uid             and
            u.name = USER)
   DROP TRIGGER DTULTATU_PRODMODFILI
GO


CREATE TRIGGER DTULTATU_PRODMODFILI
ON PRODMODFILI
FOR INSERT, DELETE
AS

BEGIN
   IF (0 = (SELECT COUNT(*) FROM DELETED))
   BEGIN
   	UPDATE PRODMODFILI
   	   SET DTULTATU = GETDATE()
   	  FROM INSERTED
   	 WHERE PRODMODFILI.CDFILIAL     = INSERTED.CDFILIAL
   	   AND PRODMODFILI.CDMODULOPROD = INSERTED.CDMODULOPROD
   	   AND PRODMODFILI.CDPRODUTO    = INSERTED.CDPRODUTO
   END;

   IF (0 = (SELECT COUNT(*) FROM INSERTED))
   BEGIN
   	INSERT INTO DELETECACHE (NMTABLECACHE, CDFILICACHE, DSKEYCACHE, DTULTATUCACH)
   		(SELECT 'PRODMODFILI', CDFILIAL, 'CDFILIAL=' + CDFILIAL  +
   	                            ';'+ 'CDMODULOPROD=' + CDMODULOPROD +
   				           ';'+ 'CDPRODUTO=' + CDPRODUTO + ';', GETDATE() FROM DELETED)
   END;
END;
GO

UPDATE PRODMODFILI SET DTULTATU = CONVERT(DATETIME,CONVERT(VARCHAR,GETDATE(),103)+' '+CONVERT(VARCHAR,GETDATE(),108)) WHERE DTULTATU IS NULL
GO

IF EXISTS(SELECT * FROM sysobjects O
          WHERE
            o.name = 'DEFAULT_DTULTATUPRODMODFILI' and
            type = 'D')
   ALTER TABLE PRODMODFILI DROP CONSTRAINT DEFAULT_DTULTATUPRODMODFILI
GO

ALTER TABLE PRODMODFILI ADD CONSTRAINT DEFAULT_DTULTATUPRODMODFILI
DEFAULT CONVERT(DATETIME,CONVERT(VARCHAR,GETDATE(),103)+' '+CONVERT(VARCHAR,GETDATE(),108))
FOR DTULTATU
GO

-- VERSAO --
EXEC ATUVEROBJ 'DTULTATU_PRODMODFILI','5.07.026';
GO