IF EXISTS (SELECT * FROM SYSOBJECTS O, SYSUSERS U
           WHERE O.NAME = 'GERA_SOLICITA_EXTRA' AND
                 TYPE = 'TR'         AND
                  U.UID = O.UID             AND
                  U.NAME = USER)
DROP TRIGGER GERA_SOLICITA_EXTRA
GO

CREATE  TRIGGER GERA_SOLICITA_EXTRA
ON SOLICITA
FOR UPDATE

AS
  IF(SELECT IDSOLEXTRA FROM DELETED) <> (SELECT IDSOLEXTRA FROM INSERTED) BEGIN

    DECLARE @V_NEW_CDFILSOLI  VARCHAR(4);
    DECLARE @V_NEW_CDFILLANCA VARCHAR(4);
    DECLARE @V_NEW_NRSOLICMP  VARCHAR(10);
    DECLARE @V_NEW_IDSOLEXTRA VARCHAR(1);
    DECLARE @V_OLD_CDFILSOLI  VARCHAR(4);
    DECLARE @V_OLD_CDFILLANCA VARCHAR(4);
    DECLARE @V_OLD_NRSOLICMP  VARCHAR(10);
    DECLARE @V_OLD_IDSOLEXTRA VARCHAR(1);
    
    BEGIN
      DECLARE C_CURSOR CURSOR FOR
        SELECT
               INSERTED.CDFILSOLI,
               INSERTED.CDFILLANCA,
               INSERTED.NRSOLICMP,
               INSERTED.IDSOLEXTRA,
               DELETED.CDFILSOLI,
               DELETED.CDFILLANCA,
               DELETED.NRSOLICMP,
               DELETED.IDSOLEXTRA
          FROM
               INSERTED,
               DELETED
         WHERE
               INSERTED.CDFILSOLI    =  DELETED.CDFILSOLI   AND
               INSERTED.CDFILLANCA   =  DELETED.CDFILLANCA AND
               INSERTED.NRSOLICMP    =  DELETED.NRSOLICMP   AND
               INSERTED.IDSOLEXTRA   =  DELETED.IDSOLEXTRA;

        OPEN C_CURSOR;
        FETCH NEXT FROM C_CURSOR INTO @V_NEW_CDFILSOLI,
                                     @V_NEW_CDFILLANCA,
                                     @V_NEW_NRSOLICMP,
                                     @V_NEW_IDSOLEXTRA,
                                     @V_OLD_CDFILSOLI,
                                     @V_OLD_CDFILLANCA,
                                     @V_OLD_NRSOLICMP,
                                     @V_OLD_IDSOLEXTRA;

        WHILE (@@FETCH_STATUS = 0) BEGIN
          UPDATE ITEMSOLI
             SET IDITMSOLEXTRA = ISNULL(@V_NEW_IDSOLEXTRA, @V_OLD_IDSOLEXTRA)
           WHERE CDFILSOLI     = ISNULL(@V_NEW_CDFILSOLI,  @V_OLD_CDFILSOLI)
             AND CDFILLAN      = ISNULL(@V_NEW_CDFILLANCA, @V_OLD_CDFILLANCA)
             AND NRSOLICMP     = ISNULL(@V_NEW_NRSOLICMP,  @V_OLD_NRSOLICMP);

          FETCH NEXT FROM C_CURSOR INTO @V_NEW_CDFILSOLI,
                                        @V_NEW_CDFILLANCA,
                                        @V_NEW_NRSOLICMP,
                                        @V_NEW_IDSOLEXTRA,
                                        @V_OLD_CDFILSOLI,
                                        @V_OLD_CDFILLANCA,
                                        @V_OLD_NRSOLICMP,
                                        @V_OLD_IDSOLEXTRA;
        END;
        CLOSE      C_CURSOR;
        DEALLOCATE C_CURSOR;
    END;
END;
GO

-- VERSAO --
EXEC ATUVEROBJ 'GERA_SOLICITA_EXTRA','5.65.XXX';
GO
