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

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

UPDATE SETORPRODOBS 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_DTULTATUSETORPRODOBS' and
            type = 'D')
   ALTER TABLE SETORPRODOBS DROP CONSTRAINT DEFAULT_DTULTATUSETORPRODOBS
GO

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

-- VERSAO --
EXEC ATUVEROBJ 'DTULTATU_SETORPRODOBS','5.85.000';
GO