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

CREATE TRIGGER DTULTATU_FERICARD
ON FERICARD
FOR INSERT, UPDATE, DELETE
AS
BEGIN
   IF (0 = (SELECT COUNT(*) FROM INSERTED)) BEGIN
      INSERT INTO DELETECACHE (NMTABLECACHE, CDFILICACHE, DSKEYCACHE, DTULTATUCACH)
			      (SELECT 'FERICARD', '', 'CDFILIAL='  + CDFILIAL  + ';'+
                                                            'DTFERICARD='+ CONVERT(CHAR,DTFERICARD,120)+ ';', CONVERT(DATETIME,CONVERT(VARCHAR,GETDATE(),103)+' '+CONVERT(VARCHAR,GETDATE(),108)) FROM DELETED)
   END
   ELSE BEGIN
      UPDATE FERICARD
         SET DTULTATU = CONVERT(DATETIME,CONVERT(VARCHAR,GETDATE(),103)+' '+CONVERT(VARCHAR,GETDATE(),108))
        FROM INSERTED
       WHERE (ISNULL(FERICARD.CDFILIAL,0)   = ISNULL(INSERTED.CDFILIAL,0))
         AND (ISNULL(FERICARD.DTFERICARD,CONVERT(DATETIME,'31/12/1899')) = ISNULL(INSERTED.DTFERICARD,CONVERT(DATETIME,'31/12/1899')));
   END;
END;
GO

UPDATE FERICARD 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_DTULTATUFERICARD' and
            type = 'D')
   ALTER TABLE FERICARD DROP CONSTRAINT DEFAULT_DTULTATUFERICARD
GO

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

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