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

CREATE TRIGGER ATUALIZA_NRSEQ_ROTFABLOCAL
ON ROTFABLOCAL
INSTEAD OF INSERT
AS

DECLARE @V_SEQUENCIAL     VARCHAR(20);
DECLARE @V_CHAVE          VARCHAR(40);
DECLARE @V_NRSEQROTFABLOC VARCHAR(10);

BEGIN
   SELECT @V_CHAVE = 'ROTFABLOCAL'+INSERTED.CDFILIAL+INSERTED.CDPRODUTO+INSERTED.CDSUBPRODLOC
     FROM INSERTED;

   EXEC NOVO_CODIGO @V_CHAVE, @P_SEQUENCIAL = @V_SEQUENCIAL OUTPUT, @P_QTDE = 1;
   SET @V_NRSEQROTFABLOC = RIGHT(REPLICATE('0', 10) + SUBSTRING(@V_SEQUENCIAL, 11, 10), 10);

   INSERT INTO ROTFABLOCAL
      (CDFILIAL, CDPRODUTO, CDSUBPRODLOC, NRSEQROTFABLOC, QTSUBPRODLOC, NRHRFABPRLOC, NRSEQPRODLOC,
       IDIMPPROTLOC, CDDEPTO, DSAPELIDOKDS, IDLOCGERAPEDORCAEVE, DTINIVGPRODLOC, DTFINVGPRODLOC)
   SELECT INSERTED.CDFILIAL, INSERTED.CDPRODUTO, INSERTED.CDSUBPRODLOC, @V_NRSEQROTFABLOC, INSERTED.QTSUBPRODLOC, INSERTED.NRHRFABPRLOC, INSERTED.NRSEQPRODLOC,
          INSERTED.IDIMPPROTLOC, INSERTED.CDDEPTO, INSERTED.DSAPELIDOKDS, INSERTED.IDLOCGERAPEDORCAEVE, INSERTED.DTINIVGPRODLOC, INSERTED.DTFINVGPRODLOC
     FROM INSERTED;
END;
GO

-- VERSAO --
EXEC ATUVEROBJ 'ATUALIZA_NRSEQ_ROTFABLOCAL','6.39.030';
GO
