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

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

UPDATE SETORFILIAL 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_DTULTATUSETORFILIAL' and
            type = 'D')
   ALTER TABLE SETORFILIAL DROP CONSTRAINT DEFAULT_DTULTATUSETORFILIAL
GO

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

-- VERSAO --
EXEC ATUVEROBJ 'DTULTATU_SETORFILIAL','6.05.000';
GO