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

CREATE  PROCEDURE ARQDIGITAL_BLCA
     @P_CDEMPRESA    VARCHAR(4000),
     @P_NRSEQARQMAG  VARCHAR(4000), 
     @P_RETURN       NUMERIC OUTPUT  
AS
   BEGIN
   DECLARE   @V_REGAAAAA    NUMERIC;
   DECLARE   @V_ARQ_0001    VARCHAR(4000);

   /* ABERTURA DO BLOCO A */
   DECLARE C_REGA001 CURSOR FOR (SELECT ('|A001'        	   + '|' +
                                         '1'                 	   + '|' +
                                         ISNULL(M.CDMUNICIBGE, '') + '|'  ) AS ARQ_A001
                                   FROM  EMPRESA E, MUNICIPIO M
                                  WHERE  E.CDPAIS      = M.CDPAIS      AND
                                         E.SGESTADO    = M.SGESTADO    AND
                                         E.CDMUNICIPIO = M.CDMUNICIPIO AND
                                         E.CDEMPRESA   = @P_CDEMPRESA)
   OPEN C_REGA001;
   FETCH NEXT FROM C_REGA001 INTO @V_ARQ_0001;

   WHILE (@@FETCH_STATUS = 0) BEGIN 
      INSERT INTO ARQMAGNETICO
      (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
      VALUES
      ('11'+RIGHT(REPLICATE('0',8)+RTRIM('1'), 8), @V_ARQ_0001, @P_NRSEQARQMAG);
      SET @V_REGAAAAA = ISNULL(@V_REGAAAAA,0) + 1;
      FETCH NEXT FROM C_REGA001 INTO @V_ARQ_0001;
   END;
   CLOSE      C_REGA001 
   DEALLOCATE C_REGA001;

   /* ENCERRAMENTO DO BLOCO A */
   SET @V_REGAAAAA = ISNULL(@V_REGAAAAA,0) + 1;
   INSERT INTO ARQMAGNETICO
     (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
   VALUES
     ('12'+RIGHT(REPLICATE('0',8)+RTRIM('2'), 8), '|A990' + '|' +'2'+ '|', @P_NRSEQARQMAG);

   SET @P_RETURN = @V_REGAAAAA; 
END
GO

-- VERSAO --
EXEC ATUVEROBJ 'ARQDIGITAL_BLCA','5.05.008';
GO

