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

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

UPDATE SETORLOJA 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_DTULTATUSETORLOJA' and
            type = 'D')
   ALTER TABLE SETORLOJA DROP CONSTRAINT DEFAULT_DTULTATUSETORLOJA
GO

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

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