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

CREATE TRIGGER DTULTATU_CONSUMIFILIAL
ON CONSUMIFILIAL
FOR INSERT, UPDATE, DELETE
AS
BEGIN
   IF (0 = (SELECT COUNT(*) FROM INSERTED)) BEGIN
      INSERT INTO DELETECACHE (NMTABLECACHE, CDFILICACHE, DSKEYCACHE, DTULTATUCACH)
			      (SELECT 'CONSUMIFILIAL', '', 'CDCLIENTE='  + CDCLIENTE  + ';'+'CDCONSUMIDOR='  + CDCONSUMIDOR  + ';'+'CDFILIAL='+ CDFILIAL+ ';', CONVERT(DATETIME,CONVERT(VARCHAR,GETDATE(),103)+' '+CONVERT(VARCHAR,GETDATE(),108)) FROM DELETED)
   END
   ELSE BEGIN
      UPDATE CONSUMIFILIAL
         SET DTULTATU = CONVERT(DATETIME,CONVERT(VARCHAR,GETDATE(),103)+' '+CONVERT(VARCHAR,GETDATE(),108))
        FROM INSERTED
       WHERE (ISNULL(CONSUMIFILIAL.CDCLIENTE,0)    = ISNULL(INSERTED.CDCLIENTE,0))
         AND (ISNULL(CONSUMIFILIAL.CDCONSUMIDOR,0) = ISNULL(INSERTED.CDCONSUMIDOR,0))
         AND (ISNULL(CONSUMIFILIAL.CDFILIAL,0)     = ISNULL(INSERTED.CDFILIAL,0));
   END;
END;
GO

UPDATE CONSUMIFILIAL 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_DTULTATUCONSUMIFILIAL' and
            type = 'D')
   ALTER TABLE CONSUMIFILIAL DROP CONSTRAINT DEFAULT_DTULTATUCONSUMIFILIAL
GO

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

-- VERSAO --
EXEC ATUVEROBJ 'DTULTATU_CONSUMIFILIAL','5.09.999';
GO
