IF EXISTS(SELECT
             NAME
          FROM
             SYSOBJECTS
          WHERE
             NAME = 'ATUALIZA_LOCALALMOX' AND
             TYPE = 'TR')

DROP TRIGGER ATUALIZA_LOCALALMOX
GO

CREATE TRIGGER ATUALIZA_LOCALALMOX
ON ALMOXARIFADO
FOR INSERT

AS

DECLARE  @V_NEWCDFILIAL    VARCHAR(4);
DECLARE  @V_NEWCDALMOX     VARCHAR(6);

BEGIN

   DECLARE C_INSERTED CURSOR FOR
   SELECT CDFILIAL, CDALMOXARIFE
   FROM INSERTED
   WHERE (CDFILIAL+CDALMOXARIFE) NOT IN (SELECT CDFILIAL+CDALMOXARIFE
                                         FROM DELETED);

   OPEN C_INSERTED;

   FETCH NEXT FROM C_INSERTED INTO @V_NEWCDFILIAL, @V_NEWCDALMOX;

   WHILE (@@FETCH_STATUS = 0) BEGIN
      INSERT INTO LOCALESTOQUE
      (CDFILIAL, CDALMOXARIFE, CDLOCALESTOQ, DSLOCALESTOQ)
      (SELECT @V_NEWCDFILIAL, @V_NEWCDALMOX , ' ', ' '
       FROM PARAMGERAL
       WHERE
       NOT EXISTS
       (SELECT CDFILIAL, CDALMOXARIFE, CDLOCALESTOQ, ' '
        FROM LOCALESTOQUE
        WHERE
           CDFILIAL     = @V_NEWCDFILIAL  AND
           CDALMOXARIFE = @V_NEWCDALMOX   AND
           CDLOCALESTOQ = ' '));
      FETCH NEXT FROM C_INSERTED INTO @V_NEWCDFILIAL, @V_NEWCDALMOX;
   END;
   CLOSE C_INSERTED;
   DEALLOCATE C_INSERTED;
END;
GO

-- VERSAO --
EXEC ATUVEROBJ 'ATUALIZA_LOCALALMOXT','5.01.014';
GO

