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

CREATE  TRIGGER GERA_ITEMSOLI_EXTRA
ON ITEMSOLI
FOR INSERT

AS
   DECLARE @V_NEW_CDFILSOLI     VARCHAR(4);
   DECLARE @V_NEW_CDFILLAN      VARCHAR(4);
   DECLARE @V_NEW_NRSOLICMP     VARCHAR(10);
   DECLARE @V_NEW_CDPRODUTO     VARCHAR(10);
   DECLARE @V_NEW_DTPROGENTR    DATETIME;
   DECLARE @V_IDSOLEXTRA        VARCHAR(1);
BEGIN
   DECLARE C_CURSOR CURSOR FOR
      SELECT INSERTED.CDFILSOLI,
             INSERTED.CDFILLAN,
             INSERTED.NRSOLICMP,
             INSERTED.CDPRODUTO,
             INSERTED.DTPROGENTR
      FROM
         INSERTED
      WHERE
         0 = (SELECT COUNT(*) FROM DELETED);

   OPEN C_CURSOR;
   FETCH NEXT FROM C_CURSOR INTO @V_NEW_CDFILSOLI,
                                 @V_NEW_CDFILLAN,
                                 @V_NEW_NRSOLICMP,
                                 @V_NEW_CDPRODUTO,
                                 @V_NEW_DTPROGENTR;

   WHILE (@@FETCH_STATUS = 0) BEGIN
      SELECT @V_IDSOLEXTRA = ISNULL(MAX(IDSOLEXTRA), 'N')
        FROM SOLICITA
       WHERE SOLICITA.CDFILLANCA = @V_NEW_CDFILLAN
         AND SOLICITA.CDFILSOLI  = @V_NEW_CDFILSOLI
         AND SOLICITA.NRSOLICMP  = @V_NEW_NRSOLICMP;
      UPDATE ITEMSOLI
         SET IDITMSOLEXTRA =  @V_IDSOLEXTRA
       WHERE CDFILSOLI   = @V_NEW_CDFILSOLI
         AND CDFILLAN    = @V_NEW_CDFILLAN
         AND NRSOLICMP   = @V_NEW_NRSOLICMP
         AND CDPRODUTO   = @V_NEW_CDPRODUTO
         AND DTPROGENTR  = @V_NEW_DTPROGENTR;
      FETCH NEXT FROM C_CURSOR INTO @V_NEW_CDFILSOLI,
                                    @V_NEW_CDFILLAN,
                                    @V_NEW_NRSOLICMP,
                                    @V_NEW_CDPRODUTO,
                                    @V_NEW_DTPROGENTR;
   END;
   CLOSE      C_CURSOR;
   DEALLOCATE C_CURSOR;
END;
GO

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